"If a worker wants to do his job well, he must first sharpen his tools." - Confucius, "The Analects of Confucius. Lu Linggong"
Front page > Programming > How to Check for Row Existence Using PDO?

How to Check for Row Existence Using PDO?

Published on 2024-11-01
Browse:833

How to Check for Row Existence Using PDO?

Checking Row Existence Using PDO

You've encountered difficulty verifying row existence in a database using PDO. To address this issue, consider the following solution:

As suggested in the answer, you can directly check the return value of the query. Here's an example:

$stmt = $conn->prepare('SELECT * FROM table WHERE ID=?');
$stmt->bindParam(1, $_GET['id'], PDO::PARAM_INT);
$stmt->execute();
$row = $stmt->fetch(PDO::FETCH_ASSOC);

if (!$row) {
    echo 'Row does not exist';
}

In this code, $stmt->execute() attempts to execute the query. If no row is found, $stmt->fetch() returns FALSE. This allows you to use the if (!$row) condition to determine whether the row exists.

Additionally, if you wish to check for multiple rows or avoid fetching the row, you can use the $stmt->fetchAll() method:

$rows = $stmt->fetchAll(PDO::FETCH_ASSOC);

if (!$rows) {
    echo 'No rows found';
}

Alternatively, you can instruct MySQL to return a 1 when a row is found:

$sql = 'SELECT 1 from table WHERE id = ? LIMIT 1';
$stmt = $conn->prepare($sql);
$stmt->execute([$_GET['id']]);

if ($stmt->fetchColumn()) echo 'Row found';

This approach eliminates the need for fetching the row, improving efficiency.

Release Statement This article is reprinted at: 1729560796 If there is any infringement, please contact [email protected] to delete it
Latest tutorial More>

Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.

Copyright© 2022 湘ICP备2022001581号-3