In this article, You will learn how to connect mysql using command line (CMD) and php source code.
How to connect to MySQL Database using Command Line and PHP Script/Code?
Here are ways:
- MySQL Connect Using Command Line
- PHP Database Connection with MySQL
MySQL Connect Using Command Line
Steps to connect MySQL from using command line:
1. Log in to your Hosting account using SSH
On the command line, write the following command, replace USERNAME to your USERNAME :-
mysql -u USERNAME -p
2. Enter Password
At the password prompt, type your password. When you type the correct password, mysql> prompts are displayed.
3. To See List of Database
To display a list of databases, Use the below command at the mysql> prompt :-
show databases;
4. Use Database
To access a specific database, use the following command at the mysql> prompt, and also replace the DBNAME with the database you your database name :-
use DBNAME;
5. Accessed Database
After accessing the database, you can run SQL queries, list tables and so on. apart from this :-
- To see a list of MySQL commands, type help at mysql> prompt.
- To exit the Mysql program, type \ q at mysql> prompt.
PHP Database Connection with MySQL
PHP provides mysql_connect() function to open a database connection. This function takes five parameters and returns a MySQL link identifier on success or FALSE on failure.
Syntax
mysql_connect(host,username,password,new_link,client_flag);
Here is source code to connect MySQL database with php:
<?php $host= "localhost"; $username = "username"; $password = "password"; // Create connection $conn = mysqli_connect($host, $username, $password); // Check connection if (!$conn) { die("Connection failed: " . mysqli_connect_error()); } echo 'Connected successfully'; mysqli_close($conn); ?>