PHP PDO returning single row
UPDATE 2:
So is this the most optimized it can get?
$DBH = new PDO( "connection string goes here" );
$STH = $DBH -> prepare( "select figure from table1" );
$STH -> execute();
$result = $STH -> fetch();
echo $result ["figure"];
$DBH = null;
UPDATE 1:
I know I can add limit to the sql query, but I also want to get rid of the foreach loop, which I should not need.
ORIGINAL QUESTION:
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.
$DBH = new PDO( "connection string goes here" );
$STH = $DBH -> prepare( "select figure from table1" );
$STH -> execute();
$result = $STH -> fetchAll();
foreach( $result as $row ) {
echo $row["figure"];
}
$DBH = null;
Solution 1:
Just fetch. only gets one row. So no foreach loop needed :D
$row = $STH -> fetch();
example (ty northkildonan):
$id = 4;
$stmt = $dbh->prepare("SELECT name FROM mytable WHERE id=? LIMIT 1");
$stmt->execute([$id]);
$row = $stmt->fetch();
Solution 2:
$DBH = new PDO( "connection string goes here" );
$STH - $DBH -> prepare( "select figure from table1 ORDER BY x LIMIT 1" );
$STH -> execute();
$result = $STH -> fetch();
echo $result ["figure"];
$DBH = null;
You can use fetch and LIMIT together. LIMIT has the effect that the database returns only one entry so PHP has to handle very less data. With fetch you get the first (and only) result entry from the database reponse.
You can do more optimizing by setting the fetching type, see http://www.php.net/manual/de/pdostatement.fetch.php. If you access it only via column names you need to numbered array.
Be aware of the ORDER clause. Use ORDER or WHERE to get the needed row. Otherwise you will get the first row in the table alle the time.