- PHP Connect to MySQL
- Should I Use MySQLi or PDO?
- MySQL Examples in Both MySQLi and PDO Syntax
- MySQLi Installation
- PDO Installation
- Open a Connection to MySQL
- Example (MySQLi Object-Oriented)
- Example (MySQLi Procedural)
- Example (PDO)
- Close the Connection
- Connections and Connection management
- User Contributed Notes
PHP Connect to MySQL
PHP 5 and later can work with a MySQL database using:
- MySQLi extension (the «i» stands for improved)
- PDO (PHP Data Objects)
Earlier versions of PHP used the MySQL extension. However, this extension was deprecated in 2012.
Should I Use MySQLi or PDO?
If you need a short answer, it would be «Whatever you like».
Both MySQLi and PDO have their advantages:
PDO will work on 12 different database systems, whereas MySQLi will only work with MySQL databases.
So, if you have to switch your project to use another database, PDO makes the process easy. You only have to change the connection string and a few queries. With MySQLi, you will need to rewrite the entire code — queries included.
Both are object-oriented, but MySQLi also offers a procedural API.
Both support Prepared Statements. Prepared Statements protect from SQL injection, and are very important for web application security.
MySQL Examples in Both MySQLi and PDO Syntax
In this, and in the following chapters we demonstrate three ways of working with PHP and MySQL:
MySQLi Installation
For Linux and Windows: The MySQLi extension is automatically installed in most cases, when php5 mysql package is installed.
PDO Installation
Open a Connection to MySQL
Before we can access data in the MySQL database, we need to be able to connect to the server:
Example (MySQLi Object-Oriented)
$servername = «localhost»;
$username = «username»;
$password = «password»;
?php
// 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:
$connect_error was broken until PHP 5.2.9 and 5.3.0. If you need to ensure compatibility with PHP versions prior to 5.2.9 and 5.3.0, use the following code instead:
// Check connection
if (mysqli_connect_error()) die(«Database connection failed: » . mysqli_connect_error());
>
Example (MySQLi Procedural)
$servername = «localhost»;
$username = «username»;
$password = «password»;
?php
// Create connection
$conn = mysqli_connect($servername, $username, $password);
// Check connection
if (!$conn) die(«Connection failed: » . mysqli_connect_error());
>
echo «Connected successfully»;
?>
Example (PDO)
$servername = «localhost»;
$username = «username»;
$password = «password»;
?php
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 have also specified a database (myDB). PDO require a valid database to connect to. If no database is specified, an exception is thrown.
Tip: A great benefit of PDO is that it has an exception class to handle any problems that may occur in our database queries. If an exception is thrown within the try < >block, the script stops executing and flows directly to the first catch() < >block.
Close the Connection
The connection will be closed automatically when the script ends. To close the connection before, use the following:
Connections and Connection management
Connections are established by creating instances of the PDO base class. It doesn’t matter which driver you want to use; you always use the PDO class name. The constructor accepts parameters for specifying the database source (known as the DSN) and optionally for the username and password (if any).
Example #1 Connecting to MySQL
If there are any connection errors, a PDOException object will be thrown. You may catch the exception if you want to handle the error condition, or you may opt to leave it for an application global exception handler that you set up via set_exception_handler() .
Example #2 Handling connection errors
try $dbh = new PDO ( ‘mysql:host=localhost;dbname=test’ , $user , $pass );
foreach( $dbh -> query ( ‘SELECT * from FOO’ ) as $row ) print_r ( $row );
>
$dbh = null ;
> catch ( PDOException $e ) print «Error!: » . $e -> getMessage () . «
» ;
die();
>
?>?php
If your application does not catch the exception thrown from the PDO constructor, the default action taken by the zend engine is to terminate the script and display a back trace. This back trace will likely reveal the full database connection details, including the username and password. It is your responsibility to catch this exception, either explicitly (via a catch statement) or implicitly via set_exception_handler() .
Upon successful connection to the database, an instance of the PDO class is returned to your script. The connection remains active for the lifetime of that PDO object. To close the connection, you need to destroy the object by ensuring that all remaining references to it are deleted—you do this by assigning null to the variable that holds the object. If you don’t do this explicitly, PHP will automatically close the connection when your script ends.
Note: If there are still other references to this PDO instance (such as from a PDOStatement instance, or from other variables referencing the same PDO instance), these have to be removed also (for instance, by assigning null to the variable that references the PDOStatement).
Example #3 Closing a connection
$dbh = new PDO ( ‘mysql:host=localhost;dbname=test’ , $user , $pass );
// use the connection here
$sth = $dbh -> query ( ‘SELECT * FROM foo’ );
?php
// and now we’re done; close it
$sth = null ;
$dbh = null ;
?>
Many web applications will benefit from making persistent connections to database servers. Persistent connections are not closed at the end of the script, but are cached and re-used when another script requests a connection using the same credentials. The persistent connection cache allows you to avoid the overhead of establishing a new connection every time a script needs to talk to a database, resulting in a faster web application.
Example #4 Persistent connections
$dbh = new PDO ( ‘mysql:host=localhost;dbname=test’ , $user , $pass , array(
PDO :: ATTR_PERSISTENT => true
));
?>?php
The value of the PDO::ATTR_PERSISTENT option is converted to bool (enable/disable persistent connections), unless it is a non-numeric string , in which case it allows to use multiple persistent connection pools. This is useful if different connections use incompatible settings, for instance, different values of PDO::MYSQL_ATTR_USE_BUFFERED_QUERY .
Note:
If you wish to use persistent connections, you must set PDO::ATTR_PERSISTENT in the array of driver options passed to the PDO constructor. If setting this attribute with PDO::setAttribute() after instantiation of the object, the driver will not use persistent connections.
Note:
If you’re using the PDO ODBC driver and your ODBC libraries support ODBC Connection Pooling (unixODBC and Windows are two that do; there may be more), then it’s recommended that you don’t use persistent PDO connections, and instead leave the connection caching to the ODBC Connection Pooling layer. The ODBC Connection Pool is shared with other modules in the process; if PDO is told to cache the connection, then that connection would never be returned to the ODBC connection pool, resulting in additional connections being created to service those other modules.
User Contributed Notes
- PDO
- Introduction
- Installing/Configuring
- Predefined Constants
- Connections and Connection management
- Transactions and auto-commit
- Prepared statements and stored procedures
- Errors and error handling
- Large Objects (LOBs)
- PDO
- PDOStatement
- PDOException
- PDO Drivers