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

Introduction to the mysqli_query() function

The mysqli_query() function is a built-in function in PHP that is used to execute an SQL query against a MySQL database. The mysqli_query() function returns a result set object, which contains the results of the query.

How to use the mysqli_query() function

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

<?php
$mysqli = new mysqli("localhost", "username", "password", "database");

if ($mysqli->connect_errno) {
    echo "Failed to connect to MySQL: " . $mysqli->connect_error;
    exit();
}

$query = "SELECT * FROM users";
$result = $mysqli->query($query);
if ($result) {
    while ($row = $result->fetch_assoc()) {
        // process the row
    }
    $result->free();
} else {
    echo "Query failed: " . $mysqli->error;
}

$mysqli->close();
?>

In this example, we first create a new MySQLi object using the mysqli() constructor. We then check if the connection was successful using the connect_errno property. If the connection was successful, we define an SQL query that selects all rows from the users table. We then call the mysqli_query() function with the query string to execute the query and retrieve the result set. We then check if the result set was retrieved successfully using an if statement. If the result set was retrieved successfully, we loop through the rows using the fetch_assoc() method and process each row. Finally, we free the result set using the free() method and close the connection using the close() method.

Conclusion

In conclusion, the mysqli_query() function is a powerful tool for working with MySQL databases in PHP. By understanding how to use the function, you can execute SQL queries and retrieve result sets, which can then be processed and displayed to the user.

Practice Your Knowledge

What are the examples of superglobal variables in PHP?

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?