PDO/PHP - Check if row exist

不想你离开。 提交于 2019-12-17 10:47:15

问题


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);

Tried if (count($row) == 0) and if($stmt->rowCount() < 0) but none of them works.


回答1:


You can just check the return value directly.

$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)
{
    die('nothing found');
}

/*
$rows = $stmt->fetchAll(PDO::FETCH_ASSOC); // Same here
if( ! $rows)
{
    die('nothing found');
}
*/

If you are asking about checking without fetching then simply have MySQL return a 1 (or use the COUNT() 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()) die('found');



回答2:


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 a SELECT statement. Instead, use PDO::query() to issue a SELECT COUNT(*) statement with the same predicates as your intended SELECT statement, then use PDOStatement::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.




回答3:


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;
    }
}


来源:https://stackoverflow.com/questions/11974613/pdo-php-check-if-row-exist

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!