# How to Connect PHP with MySQL Database

# **1\. Prerequisites**

Before you start, ensure the following:

* PHP is installed on your server or localhost (e.g., XAMPP, WAMP, or LAMP).
    
* MySQL server is running, and you have access credentials (host, username, password, and database name).
    

Click: [https://phpgurukul.com/connect-php-mysql-database/](https://phpgurukul.com/connect-php-mysql-database/)

# **2\. Basic PHP-MySQL Connection Setup**

Below is the typical structure to connect PHP with MySQL using the `mysqli` extension:

```plaintext
php
```

```plaintext
Copy code
```

```plaintext
<?php
// Database configuration
$host = "localhost";      // Host name (usually 'localhost')
$username = "root";        // MySQL username
$password = "";            // MySQL password (leave empty for localhost setup)
$database = "test_db";     // Database name
```

```plaintext
// Create a connection
$conn = new mysqli($host, $username, $password, $database);// Check connection
if ($conn->connect_error) {
    die("Connection failed: " . $conn->connect_error);
}
echo "Connected successfully";
?>
```

# **3\. Explanation of the Code**

* `$host`**:** The server name where your MySQL database is hosted (usually `'localhost'` for development).
    
* `$username` **and** `$password`**:** The credentials used to access the database.
    
* `$database`**:** The name of the database you want to connect to.
    
* `new mysqli()`: Creates a new connection object using the provided parameters.
    
* `$conn->connect_error`: Checks if there was an error during connection.
    

# **4\. Handling Connection Errors Gracefully**

Instead of halting the script abruptly with `die()`, you can handle errors more gracefully using:

```plaintext
php
```

```plaintext
Copy code
```

```plaintext
<?php
if ($conn->connect_error) {
    echo "Connection failed: " . $conn->connect_error;
} else {
    echo "Connected successfully";
}
?>
```

# **5\. Making Queries (CRUD Operations)**

Once connected, you can interact with the database. Here’s a quick example to **insert data** into a table:

```plaintext
php
```

```plaintext
Copy code
```

```plaintext
$sql = "INSERT INTO users (username, email) VALUES ('john_doe', 'john@example.com')";
if ($conn->query($sql) === TRUE) {
    echo "New record created successfully";
} else {
    echo "Error: " . $sql . "<br>" . $conn->error;
}
```

# **6\. Closing the Connection**

Always close the connection once you’re done to free up resources:

```plaintext
php
```

```plaintext
Copy code
```

```plaintext
$conn->close();
```

# **7\. Full Working Example**

```plaintext
php
```

```plaintext
Copy code
```

```plaintext
<?php
$host = "localhost";
$username = "root";
$password = "";
$database = "test_db";
```

```plaintext
$conn = new mysqli($host, $username, $password, $database);if ($conn->connect_error) {
    echo "Connection failed: " . $conn->connect_error;
} else {
    echo "Connected successfully<br>";    $sql = "INSERT INTO users (username, email) VALUES ('john_doe', 'john@example.com')";
    if ($conn->query($sql) === TRUE) {
        echo "New record created successfully";
    } else {
        echo "Error: " . $sql . "<br>" . $conn->error;
    }    $conn->close();
}
?>
```

# **8\. Alternative: PDO Connection**

`PDO` (PHP Data Objects) offers a more secure and flexible way to connect with MySQL. Here's an example:

```plaintext
php
```

```plaintext
Copy code
```

```plaintext
<?php
try {
    $conn = new PDO("mysql:host=localhost;dbname=test_db", "root", "");
    $conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
    echo "Connected successfully"; 
} catch(PDOException $e) {
    echo "Connection failed: " . $e->getMessage();
}
?>
```

# **Conclusion**

This guide introduces both `mysqli` and `PDO` for connecting PHP with MySQL. Use `mysqli` for simplicity and `PDO` when you need enhanced security and support for multiple databases.

PHP Gurukul

Welcome to PHPGurukul. We are a web development team striving our best to provide you with an unusual experience with PHP. Some technologies never fade, and PHP is one of them. From the time it has been introduced, the demand for PHP Projects and PHP developers is growing since 1994. We are here to make your PHP journey more exciting and useful.

Website : [https://phpgurukul.com](https://phpgurukul.com/)
