PHP 5 and later versions can interact with a MySQL database using:
Earlier versions of PHP used the MySQL extension, which was deprecated in 2012.
For a brief answer, it’s “Whatever you prefer.”
Both MySQLi and PDO have their strengths:
In this chapter and the following ones, we will demonstrate three methods for working with PHP and MySQL:
For both Linux and Windows: The MySQLi extension is usually installed automatically when you install the php5-mysql
package.
For installation details, visit: http://php.net/manual/en/mysqli.installation.php
For installation details, visit: http://php.net/manual/en/pdo.installation.php
Before accessing data in the MySQL database, we must first establish a connection to the server.
<?php $servername = “localhost”; $username = “username”; $password = “password”; // Create connection $conn = new mysqli($servername, $username, $password); // Check connection if ($conn->connect_error) { die(“Connection failed: “ . $conn->connect_error); } echo “Connected successfully”; ?> |
Note on the object-oriented example above: The $connect_error variable was unreliable before PHP 5.2.9 and 5.3.0. For compatibility with PHP versions earlier than 5.2.9 and 5.3.0, use the following code instead: // Check connection |
<?php $servername = “localhost”; $username = “username”; $password = “password”; // Create connection $conn = mysqli_connect($servername, $username, $password); // Check connection if (!$conn) { die(“Connection failed: “ . mysqli_connect_error()); } echo “Connected successfully”; ?> |
<?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(); } ?> |
Note: In the PDO example above, we also specified a database (myDB ). PDO requires a valid database to connect to; if no database is specified, an exception will be thrown. |
Tip: One of the key advantages of PDO is its exception handling capability. It includes an exception class to manage issues that arise during database queries. If an exception occurs within the try { }
block, the script halts and immediately transfers control to the first catch { }
block.
The connection will close automatically when the script ends. To close it earlier, use the following:
$conn->close(); |
mysqli_close($conn); |
$conn = null; |