Integrating PHP with MySQL database

Here's an overview of integrating PHP with MySQL database:

  1. Connecting to the database: Before working with a MySQL database, you need to establish a connection to it. This is typically done using the mysqli_connect() function. Here's an example:

    $host = "localhost"; // The database server host
    $user = "username"; // The database username
    $password = "password"; // The database password
    $database = "mydatabase"; // The name of the database to connect to
    
    $conn = mysqli_connect($host, $user, $password, $database);
    
    if (!$conn) {
        die("Connection failed: " . mysqli_connect_error());
    }

    In this example, we're connecting to a MySQL database on the local server using the username and password specified. If the connection fails, an error message is displayed.

  2. Executing SQL queries: Once you have established a connection to the database, you can execute SQL queries using the mysqli_query() function. Here's an example:

    $sql = "SELECT * FROM users";
    $result = mysqli_query($conn, $sql);
    
    if (mysqli_num_rows($result) > 0) {
        while ($row = mysqli_fetch_assoc($result)) {
            echo "ID: " . $row["id"] . " - Name: " . $row["name"] . "<br>";
        }
    } else {
        echo "0 results";
    }

    In this example, we're executing a SELECT query to retrieve all rows from the users table. We're then using a while loop to iterate over the rows and display the id and name fields for each row.

  3. Closing the connection: When you're finished working with the database, it's a good practice to close the connection using the mysqli_close() function. Here's an example:

    mysqli_close($conn);

    This will close the connection to the database.

Overall, integrating PHP with MySQL involves establishing a connection to the database, executing SQL queries, and closing the connection when finished.

Here's a complete example that demonstrates the above concepts:

<?php
$host = "localhost";
$user = "username";
$password = "password";
$database = "mydatabase";

$conn = mysqli_connect($host, $user, $password, $database);

if (!$conn) {
    die("Connection failed: " . mysqli_connect_error());
}

$sql = "SELECT * FROM users";
$result = mysqli_query($conn, $sql);

if (mysqli_num_rows($result) > 0) {
    while ($row = mysqli_fetch_assoc($result)) {
        echo "ID: " . $row["id"] . " - Name: " . $row["name"] . "<br>";
    }
} else {
    echo "0 results";
}

mysqli_close($conn);
?>

This code connects to a MySQL database, executes a SELECT query to retrieve all rows from the users table, and displays the id and name fields for each row.

Last updated