📜  php mysql connect - PHP (1)

📅  最后修改于: 2023-12-03 15:18:20.440000             🧑  作者: Mango

PHP MySQL Connect

In PHP, connecting to a MySQL database is an essential task for many web applications. This guide will teach you how to connect to a MySQL database using PHP.

Prerequisites

Before we begin, you will need the following:

  • Access to a MySQL Server with a database
  • PHP installed on your computer or server
Steps
  1. First, you need to create a connection to your MySQL server. To do this, we will use the mysqli_connect() function. Here is an example:

    $hostname = 'localhost';
    $username = 'root';
    $password = '';
    $database = 'mydatabase';
    
    // Create connection
    $con = mysqli_connect($hostname, $username, $password, $database);
    
    // Check connection
    if (!$con) {
        die('Connection failed: ' . mysqli_connect_error());
    }
    

    In this example, we are connecting to a MySQL server on the localhost with a username of root and no password. We are also selecting the mydatabase database.

  2. Now that we have a connection, we can use it to perform queries on the database. Here is an example:

    // Perform query
    $query = 'SELECT * FROM users';
    $result = mysqli_query($con, $query);
    
    // Check for errors
    if (!$result) {
        die('Query failed: ' . mysqli_error($con));
    }
    
    // Loop through results
    while ($row = mysqli_fetch_assoc($result)) {
        echo $row['name'] . ' ' . $row['email'] . '<br>';
    }
    
    // Free result set
    mysqli_free_result($result);
    

    In this example, we are performing a SELECT query on a table named users and then looping through the results and printing the name and email columns.

  3. After you are finished with your connection, you should close it. Here is an example:

    // Close connection
    mysqli_close($con);
    
Conclusion

In this guide, we have learned how to connect to a MySQL database using PHP. This is a fundamental skill for any PHP programmer, and it will help you build powerful web applications that interact with a database.