In this article, we will discuss the mysqli_real_query() function in PHP, which is used to execute an SQL query on a MySQL database.

Introduction to the mysqli_real_query() function

The mysqli_real_query() function is a built-in function in PHP that is used to execute an SQL query on a MySQL database. This function is similar to the mysqli_query() function, but it has a few key differences. Unlike the mysqli_query() function, the mysqli_real_query() function does not automatically retrieve the result set of the query. This means that you must use the mysqli_use_result() or mysqli_store_result() functions to retrieve the result set, depending on whether the query returns a result set or not.

How to use the mysqli_real_query() function

Using the mysqli_real_query() function is straightforward. Here's an example:

<?php
$con = mysqli_connect('localhost', 'username', 'password', 'database');

if (!$con) {
    die('Could not connect: ' . mysqli_error());
}

$sql = "SELECT * FROM customers";

if (mysqli_real_query($con, $sql)) {
    $result = mysqli_use_result($con);

    while ($row = mysqli_fetch_assoc($result)) {
        echo $row['name'] . '<br />';
    }

    mysqli_free_result($result);
} else {
    die('Error: ' . mysqli_error($con));
}

mysqli_close($con);
?>

In this example, we first establish a connection to a MySQL database using the mysqli_connect() function. We then define an SQL statement that selects all rows from a table called customers. We use the mysqli_real_query() function to execute the SQL statement, and we use the mysqli_use_result() function to retrieve the result set. We then loop through the result set using the mysqli_fetch_assoc() function and output the name column of each row. Finally, we free the result set using the mysqli_free_result() function.

Conclusion

In conclusion, the mysqli_real_query() function is a powerful tool for executing SQL queries on a MySQL database in PHP. By using this function, you can perform complex database operations and retrieve the result set in a secure and efficient manner.

Practice Your Knowledge

What does the PHP mysqli_real_query() function do?

Quiz Time: Test Your Skills!

Ready to challenge what you've learned? Dive into our interactive quizzes for a deeper understanding and a fun way to reinforce your knowledge.

Do you find this helpful?