PHP check if MySQL row found for query

If you want to check if a row will be returned using PHP and MySQL you can use mysqli_num_rows which counts how many rows will be returned from the query.

In the code example below it checks if the rows returned is greater than 0, in other words is there a result found where id = id in the players table. If we do have a math for id = id in the table it will output the formatted data else it will say No entry found for user id: 1234

$query = "SELECT id, name, score FROM `players` WHERE `id` = '$user_id'";
$result = mysqli_query($connect, $query);
if (mysqli_num_rows($result) > 0) {
    while ($row = $result->fetch_assoc()) {
        $name = $row['name'];
        $score = $row['score'];
        echo "$user_id is $name and has a score of $score";
} else {
    echo "No entry found for user id: $user_id";


Another use for this can be setting limits or applying limits. Check how many rows are found in a table and if its >= (equal or greater than) the limit number then we can choose the display.

$query = "SELECT id, name, date, dir1, dir2, dir3, co-ords FROM `objects` WHERE `id` = '$obj_id'";
$result = mysqli_query($connect, $query);
if (mysqli_num_rows($result) >= 200) {
    echo "The limit of 200 has been met, please delete entries to continue use";
} elseif (mysqli_num_rows($result) = 100) {
    echo "You have used up half of the MySQL row allotment";
} else {
    // output our query results.....

Using checks for rows returned is handy to avoid errors and to better handle your PHP interaction with MySQL.