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.
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