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:
$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) {
echo "Error executing query: " . $mysqli->error;
exit();
}
while ($row = $result->fetch_assoc()) {
echo "User ID: " . $row["id"] . "<br>";
echo "Name: " . $row["name"] . "<br>";
echo "Email: " . $row["email"] . "<br><br>";
}
$result->free();
$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.