Categories: Development

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.

 

Share

Recent Posts

Kennington reservoir drained drone images

A drained and empty Kennington reservoir images from a drone in early July 2024. The…

2 years ago

Merrimu Reservoir drone images

Merrimu Reservoir from drone. Click images to view larger.

2 years ago

Early September spring shots

Some early September spring shots from a bushwalk, It is still too early for wildflowers.

3 years ago

Cloning an NVMe to SK Hynix Platinum P41 NVMe

I recently needed to clone over a smaller NVMe to a 2TB SK Hynix Platinum…

3 years ago

Using Laravel’s deleteDirectory to delete folders and their contents

If you ever needed a simple solution in Laravel to delete an entire directory and…

3 years ago

How to allow only 1 user to register in a Laravel application

How to enforce only one user to register or be registered in a Laravel web…

3 years ago