Labs ICT
โญ Pro Login

MySQL Connect

2 min read | PHP Tutorial
โญ

Want the full learning experience?

Get structured courses, certificates, projects, and instructor support with LabsICT Pro.

Explore Pro Courses

Before PHP can talk to MySQL, you need to open a connection. The classic way is with mysqli_connect(). You give it the server, username, password, and database name, and if everything works, you get a connection object you can use to run queries.

Connecting with mysqli_connect

Pass four arguments to mysqli_connect(): the host (usually localhost), your username, your password, and the database name. It returns a connection object. If it fails, it returns false, and mysqli_connect_error() tells you what went wrong.

<?php
$conn = mysqli_connect("localhost", "root", "", "mydb");
if (!$conn) {
    die("Connection failed: " . mysqli_connect_error());
}
echo "Connected successfully";
?>

PDO vs MySQLi

PHP actually gives you two ways to talk to MySQL: MySQLi (MySQL improved) and PDO (PHP Data Objects). MySQLi is MySQL-specific and has both a procedural and object-oriented interface. PDO supports twelve different database drivers โ€” not just MySQL. PDO also supports prepared statements natively in a cleaner way. If you're starting a new project, PDO is usually the better choice.

<?php
try {
    $pdo = new PDO("mysql:host=localhost;dbname=mydb", "root", "");
    $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
    echo "Connected using PDO";
} catch (PDOException $e) {
    echo "Error: " . $e->getMessage();
}
?>

Closing the Connection

PHP automatically closes database connections when your script finishes, but it's good practice to close them explicitly when you're done. With MySQLi, use mysqli_close($conn). With PDO, set the connection object to null.

๐Ÿงช Quick Quiz

Which MySQLi function is used to prepare an SQL statement before execution?