Search code examples
phppdorow

How to check if a row exist in the database using PDO?


I want to have a condition that will perform some action when 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.


Solution

  • 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)
    {
        echo 'nothing found';
    }
    
    /* or for multiple rows */
    $rows = $stmt->fetchAll(PDO::FETCH_ASSOC); // Same here
    if( ! $rows)
    {
        echo 'nothing found';
    }
    

    If you are asking about checking without fetching then simply have MySQL return a 1. You can also bind a variable directly inside execute():

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