Simplest method to retrieve single (and only) row in SQLite using PDO

后端 未结 1 608
佛祖请我去吃肉
佛祖请我去吃肉 2021-01-28 08:52

I have this PDO

$stmt = $db->prepare(\'SELECT * FROM channels WHERE id=:id\');
$stmt->bindValue(\':id\', $id, SQLITE3_INTEGER);
$result = $stmt->execute         


        
1条回答
  •  情歌与酒
    2021-01-28 09:27

    It should be as simple as

    $row = $stmt->fetch(PDO::FETCH_ASSOC);
    

    The examples you've seen probably have something more like

    while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) { ...
    

    because they're designed to process a query result with multiple rows. But if you know you'll only ever have one row, you can just forgo the loop. Of course, this is assuming your query actually executed successfully and returned a result. It would be a good idea to at least check

    if ($row) { ...
    

    before you try to use it in your subsequent code.

    0 讨论(0)
提交回复
热议问题