mysql

PHP MySQL Database Connectivity

PHP MySQL Database Connectivity

PHP can interact with MySQL databases to store and retrieve data. The mysqli extension is used to connect to a MySQL database.

Connecting to MySQL

To connect to a MySQL database, use the mysqli_connect() function:

      
        <?php
          $conn = mysqli_connect("localhost", "root", "", "my_database");

          if (!$conn) {
            die("Connection failed: " . mysqli_connect_error());
          }
          echo "Connected successfully";
        ?>
      
    

Querying the Database

To execute a query, use the mysqli_query() function:

      
        <?php
          $result = mysqli_query($conn, "SELECT * FROM users");

          while ($row = mysqli_fetch_assoc($result)) {
            echo $row['username'] . "
"; } ?>

Closing the Connection

To close the database connection, use mysqli_close():

      
        <?php
          mysqli_close($conn); // Close connection
        ?>
      
    

Activity

Try It Yourself!

Write a PHP script that connects to a MySQL database and fetches data from a "users" table.

Quiz

Quick Quiz

  1. What function is used to connect to a MySQL database in PHP?
  2. How do you fetch data from a MySQL query result in PHP?

Answers: Use mysqli_connect() to connect. Use mysqli_fetch_assoc() to fetch data.