PDO/PHP - Check if row exist

I want to have a condition incase the row doesn't exist at all.
$stmt = $conn->prepare('SELECT * FROM table WHERE ID=?');
$stmt->bindParam(1, $_GET['id'], PDO::PARAM_INT);
$stmt->execute();
$row = $stmt->fetch(PDO::FETCH_ASSOC);
Triedif (count($row) == 0)
andif($stmt->rowCount() < 0)
but none of them works.
Answer
Solution:
You can just check the return value directly.
{-code-1}
If you are asking about checking without fetching then simply have MySQL return a1
(or use theCOUNT()
command).
$sql = 'SELECT 1 from table WHERE id = ? LIMIT 1';
//$sql = 'SELECT COUNT(*) from table WHERE param = ?'; // for checking >1 records
$stmt = $conn->prepare($sql);
$stmt->bindParam(1, $_GET['id'], PDO::PARAM_INT);
$stmt->execute();
if($stmt->fetchColumn()) echo 'found';
Answer
Solution:
if($stmt->rowCount() == 0)
should work fine, since the number of rows can't be less than zero in any event at all.
From the manual:
For most databases,
PDOStatement::rowCount()
does not return the number of rows affected by aSELECT
statement. Instead, usePDO::query()
to issue aSELECT COUNT(*)
statement with the same predicates as your intendedSELECT
statement, then usePDOStatement::fetchColumn()
to retrieve the number of rows that will be returned. Your application can then perform the correct action.
I would suggest reading up on that here.
Answer
Solution:
Heres what I use in my object classes:
function exists_by_id () {
// check if object exists by id
$stm = DB::$pdo->prepare('select count(*) from `table` where `column`=:column');
$stm->bindParam(':column', $this->column);
$stm->execute();
$res = $stm->fetchColumn();
if ($res > 0) {
return true;
}
else {
return false;
}
}
Share solution ↓
Additional Information:
Link To Answer People are also looking for solutions of the problem: please make sure the php redis extension is installed and enabled.
Didn't find the answer?
Our community is visited by hundreds of web development professionals every day. Ask your question and get a quick answer for free.
Similar questions
Find the answer in similar questions on our website.
Write quick answer
Do you know the answer to this question? Write a quick response to it. With your help, we will make our community stronger.