To interact with data stored in a MySQL database, you must establish a connection to the MySQL database server. PHP provides two main methods for connecting to MySQL: MySQLi (Improved MySQL) and PDO (PHP Data Objects).
While PDO is more versatile and supports over twelve different databases, MySQLi is tailored specifically for MySQL and offers both object-oriented and procedural APIs. MySQLi's procedural API is particularly beginner-friendly.
Tip: MySQLi provides superior performance and features for MySQL-specific projects compared to PDO.
In PHP, you can connect to MySQL using the mysqli_connect()
function. This connection is essential for all interactions between PHP and the MySQL server. Below are the basic syntaxes for connecting using MySQLi and PDO:
In these syntaxes, hostname specifies the MySQL server's host name or IP address (e.g., localhost
), username and password are the credentials for accessing MySQL, and database (if provided) is the default database for executing queries.
Below is an example demonstrating how to connect to a MySQL database server using MySQLi (both procedural and object-oriented approaches) and PDO:
<?php
/* Attempt MySQL server connection. Assuming you are running MySQL
server with default setting (user 'root' with no password) */
$link = mysqli_connect("localhost", "root", "");
// Check connection
if($link === false){
die("ERROR: Could not connect. " . mysqli_connect_error());
}
// Print host information
echo "Connect Successfully. Host info: " . mysqli_get_host_info($link);
?>
Note: By default, the username for the MySQL database server is root
and there is no password set. However, for security reasons, it's advisable to set a strong password for MySQL accounts to prevent unauthorized access to your databases.
Tip: When you set the PDO::ATTR_ERRMODE
attribute to PDO::ERRMODE_EXCEPTION
, PDO will throw exceptions whenever a database error occurs.
The connection to the MySQL database server closes automatically when the script execution ends. To close it earlier, you can use the PHP mysqli_close()
function.
<?php
/* Attempt MySQL server connection. Assuming you are running MySQL
server with default setting (user 'root' with no password) */
$link = mysqli_connect("localhost", "root", "");
// Check connection
if($link === false){
die("ERROR: Could not connect. " . mysqli_connect_error());
}
// Print host information
echo "Connect Successfully. Host info: " . mysqli_get_host_info($link);
// Close connection
mysqli_close($link);
?>