Connecting PHP to MySQL

Опубликовано: 02 Март 2026
на канале: PHP Explained
96
0

PHP 5 and newer versions can connect with MySQL using any of these two types.
MySQLi extension where i stands for improved, and PDO or PHP Data Objects.

Here is how to connect with MySQL using MySQLi extension.
We are creating a new object of MySQLi and passed the necessary parameters to create the connection. The parameters required are server name, user name, and password. Finally, we are closing connection for both OOP and POP programmings.
$server = "localhost";
$username = "username";
$password = "password";
$conn = new mysqli($server, $username, $password);
if ($conn-gt;connect_error) {
die("Connection failed: " . $conn-gt;connect_error);
}
echo "Connected successfully";
// OOP close.
$conn-gt;close();
// POP close.
mysqli_close($conn);

Here is how to connect with MySQL using PDO.
We are creating a new object of class PDO and passed the necessary parameters to create the connection with database. There are four required parameters such as server name, user name, password, and database name. Finally, we are closing the connection.
$server = "localhost";
$username = "username";
$password = "password";
$database = "project1";
try {
$conn = new PDO("mysql:host=$server;dbname=$database", $username, $password);
$conn-gt;setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
echo "Connected successfully";
} catch(PDOException $e) {
echo "Connection failed: " . $e-gt;getMessage();
}
$conn = null;

Just follow the syntax as given and update the necessary parameters details and code will be executed successfully.