PDO/PHP - Check if row exist

后端 未结 3 1136
面向向阳花
面向向阳花 2020-11-30 06:03

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[         


        
3条回答
  •  予麋鹿
    予麋鹿 (楼主)
    2020-11-30 06:06

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

提交回复
热议问题