In this section, you will learn how to connect to MySQL Server using MySQL command-line and PHP.
How connect to the MySQL server from the command?
The following commands will be used to connect to the MySQL Server.
1 |
shell>mysql -u root -p |
-u user name of the server that you connect to the MySQL Server as the user account root.
-p How to instruct MySQL to ask for a password.
You type the password for the user account root and press Enter:
1 |
Enter password: ******** |
MySQL Connection Using PHP
PHP 5 and later can work with MySQL database using: MySQLi extension (the “i” stands for improved) PDO (PHP information Objects).
Example (MySQLi Object-Oriented)
Try the following example to connect to a MySQL server in MySQLi Object-Oriented way.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 |
<?php //Your MySQL databse settings $servername = "localhost"; $username = "root"; $password = "root"; // Create connection $conn = new mysqli($servername, $username, $password); // Check connection if ($conn->connect_error) { die("Connection failed: " . $conn->connect_error); } echo "Connected successfully"; ?> |
Example (MySQLi Procedural)
Try the following example to connect to a MySQL server in MySQLi Procedural way.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 |
<?php //Your MySQL databse settings $servername = "localhost"; $username = "root"; $password = "root"; // Create connection $conn = mysqli_connect($servername, $username, $password); // Check connection if (!$conn) { die("Connection failed: " . mysqli_connect_error()); } echo "Connected successfully"; ?> |
Example (PDO)
Try the following example to connect to a MySQL server in MySQLi PDO way.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 |
<?php //Your MySQL database settings $servername = "localhost"; $username = "root"; $password = "root"; $database = "test"; try { $conn = new PDO("mysql:host=$servername;dbname=$database", $username, $password); // set the PDO error mode to exception $conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); echo "Connected successfully"; } catch (PDOException $e) { echo "Connection failed: " . $e->getMessage(); } ?> |
Close the Connection
The connection can be closed by using the following PHP functions.
1 2 3 4 5 6 7 8 9 10 11 12 |
<?php //MySQLi Object-Oriented $conn->close(); //MySQLi Procedural mysqli_close($conn); //PDO $conn = null; ?> |
What is Next?
In the next section, you will learn how to create a database in MySQL.
* Please do let us know your views on this article and what type of articles would you are interested to read
Widget not in any sidebars
