Tags
Asked 3 years ago
9 Jun 2021
Views 266
pratik

pratik posted

how to run select query in mysqli ?

how to run select query in mysqli ?
steave

steave
answered Apr 26 '23 00:00

You can run a select query in MySQLi using the query () method of the MySQL object.


Here's an example:



// 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();
}

// Prepare and execute query
$query = "SELECT * FROM users";
$result = $mysqli->query($query);

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

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

// Free result set
$result->free();

// Close connection
$mysqli->close();

In this example, we create a MySQLi object and establish a connection to the database. We then execute a select query (SELECT * FROM users) 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 fetch_assoc () and output the data.

Finally, we free the result set and close the connection to the database.
Post Answer