Tags
Asked 2 years ago
9 Jun 2021
Views 197
sandip

sandip posted

Query return value in case of Select with no matching rows in MySQLi

Query return value in case of Select with no matching rows in MySQLi
jabber

jabber
answered Apr 26 '23 00:00

In MySQLi, when you execute a SELECT query that doesn't match any rows, the mysqli_query () function will return false .

To handle this situation in your code, you can use the mysqli_num_rows () function to check if any rows were returned by the query. If the number of rows returned is zero, you can display an appropriate message to the user.

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

$sql = "SELECT * FROM mytable WHERE id = 123";
$result = $mysqli->query($sql);

if (!$result) {
    echo "Error executing query: " . $mysqli->error;
    exit();
}

if ($result->num_rows == 0) {
    echo "No rows found.";
    exit();
}

// Process results here
while ($row = $result->fetch_assoc()) {
    // Do something with $row
}

$result->free();
$mysqli->close();
?>

In this example, we check the result of the query using the mysqli_query () function. If it returns false , we display an error message and exit the script.

If the query is successful, we check the number of rows returned using the mysqli_num_rows () function. If it's zero, we display a message to the user and exit.

If there are rows returned, we process them in the while loop, and then free the result set and close the database connection.




Post Answer