How to connect PHP to MySQL?
PHP 5 and later can work with MySQL database using:
- MySQLi extensionÂ
- PDO (PHP Data Objects)
Which should we use MySQLi or PDO?
Both MySQLi and PDO have their returns:
- PDO will work on 12 different database systems, where MySQLi will only work with MySQL databases.
- If you have to change your project to use another database, PDO simplifies the process. You should only change the unit of connecting string and a few queries. With MySQLi, you’ll need to rewrite the entire code – with queries.
- Both are focused on the object, but MySQLi also provides a procedural API.
In short, you can choose whatever you want if you want to stick to MySQL otherwise you have to go with PDO.
Connect to MySQL using MySQLi
MySQLi Object-Oriented
<?php $servername = "localhost"; $username = "username"; $password = "password"; //Create Connection $conn = new mysqli(servername,$username,$password); //Checking Connection if ($conn->connect_error) { die("Connection failed - " . $conn->connect_error); } echo "Connected Successfully"; ?>
MySQLi Procedural
<?php $servername = "localhost"; $username = "username"; $password = "password"; //Create Connection $conn = mysqli_connect($servername,$username,$password); //Checking Connection if (!$conn) { die("Connection failed - " . mysqli_connect_error()); } echo "Connected Successfully"; ?>
Connection MySQL using PDO
<?php $servername = "localhost"; $username = "username"; $password = "password"; try { $conn = new PDO( "mysql:host=$servername;dbname=myDB", $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(); } ?>