Skip to main content

Connecting PHP to MySQL

Connecting PHP to MySQL

PHP and MySQL are two vital technologies involved in building dynamic web applications. PHP is a powerful scripting language designed to enable developers to create highly featured Web applications quickly, and MySQL is a fast, reliable database that integrates well with PHP and is suited for dynamic Internet-based applications.

This tutorial will guide you through the process of connecting PHP to MySQL database using the most popular method: MySQLi and PDO.

MySQLi Extension

MySQLi extension, or as it's more properly known MySQL improved extension, is a relational database driver used in the PHP programming language to provide an interface with MySQL databases.

Procedural Way

Here's how to connect to MySQL using MySQLi in a procedural way:

<?php
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "myDB";

// Create connection
$conn = mysqli_connect($servername, $username, $password, $dbname);

// Check connection
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
echo "Connected successfully";
mysqli_close($conn);
?>

Object-Oriented Way

Here's how to connect to MySQL using MySQLi in an object-oriented way:

<?php
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "myDB";

// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);

// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
echo "Connected successfully";
$conn->close();
?>

PDO

PHP Data Objects (PDO) defines a lightweight, consistent interface for accessing databases in PHP.

Here's how to connect to MySQL using PDO:

<?php
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "myDB";

try {
$conn = new PDO("mysql:host=$servername;dbname=$dbname", $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();
}
$conn = null;
?>

Conclusion

Connecting PHP to a MySQL database is a crucial step in developing dynamic web applications. You can choose between MySQLi and PDO depending on your specific needs and preferences. Both methods offer a secure way to connect PHP to MySQL. It's important to remember to handle exceptions and errors to ensure the stability of your web application.