Search code examples
phppdo

PHP PDO how to fetch a single row?


I have the following script which is good IMO for returning many rows from the database because of the "foreach" section.

How do I optimize this, if I know I will always only get 1 row from the database. If I know I will only ever get 1 row from the database, I don't see why I need the foreach loop, but I don't know how to change the code.

$STH = $DBH -> prepare( "select figure from table1" );
$STH -> execute();
$result = $STH -> fetchAll();
foreach( $result as $row ) {
    echo $row["figure"];
}

Solution

  • Just fetch. only gets one row. So no foreach loop needed :D

    $row = $stmt->fetch();
    

    example

    $id = 4;
    $stmt = $dbh->prepare("SELECT name FROM mytable WHERE id=? LIMIT 1"); 
    $stmt->execute([$id]); 
    $row = $stmt->fetch(PDO::FETCH_ASSOC);