PHP CHAPTER 30

MySQL Connect

A database connection allows PHP to communicate with MySQL.

📘

What is it?

A database connection allows PHP to communicate with MySQL.

💡

Why do we use it?

PHP needs a connection before it can execute database queries.

⚙️

How does it work?

MySQLi opens a connection using host, username, password and database name.

🧩

Syntax

PHP Syntax
$conn = new mysqli($host, $user, $password, $database);
💻

Example

PHP Example
<?php

$conn = new mysqli("localhost", "root", "", "aifa_php_lab");

if ($conn->connect_error) {
    die("Connection failed: " . $conn->connect_error);
}

echo "Database Connected Successfully!";

?>
🔍

Example Explained

new mysqli creates the connection. connect_error checks whether the connection failed.
🚀

More Examples

<?php require_once "config/database.php"; echo "Connected"; ?>

⚠️ Important Rules

For local XAMPP, root commonly has an empty password unless you changed it.

❌ Common Mistakes

Wrong database name, wrong password, MySQL not running or wrong host.

🌍 Real-World Use

Every PHP + MySQL application requires a database connection layer.

📝 Practice Exercise

Create config/database.php and connect it to your AIFA database.

💻 Try It Yourself

Write and run this PHP lesson inside the AIFA Coding Lab.

Open Coding Lab →