Tags
Asked 3 years ago
9 Jun 2021
Views 267
steave

steave posted

How to use mysqli_query() in php?

How to use mysqli_query() in php?
sandip

sandip
answered Apr 26 '23 00:00

mysqli_query () is a PHP function used to execute a MySQL query. Here is an example of how to use mysqli_query ():



// Establish a connection
$mysqli = new mysqli("localhost", "username", "password", "database");

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

// Execute query
$query = "SELECT * FROM users";
$result = mysqli_query($mysqli, $query);

// Check for errors and process results
if (!$result) {
    echo "Error executing query: " . mysqli_error($mysqli);
    exit();
}

// Loop through results and output data
while ($row = mysqli_fetch_assoc($result)) {
    echo "User ID: " . $row["id"] . "<br>";
    echo "Name: " . $row["name"] . "<br>";
    echo "Email: " . $row["email"] . "<br><br>";
}

// Free result set
mysqli_free_result($result);

// Close connection
mysqli_close($mysqli);

In this example, we create a MySQLi object and establish a connection to the database. We then execute a select query (SELECT * FROM users ) using mysqli_query () and store the results in a variable ($result).

We check for errors by verifying that $result is not false . If there was an error, we output the error message and exit the script.

If there were no errors, we loop through the results using mysqli_fetch_assoc () and output the data.

Finally, we free the result set using mysqli_free_result () and close the connection to the database using mysqli_close ().
Post Answer