154

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"];
}
2
  • 2
    $STH - $DBH -> prepare should be $STH = $DBH -> prepare several places on this page. Commented Jul 25, 2015 at 10:06
  • You can use foreach in break; Commented Sep 22, 2017 at 12:31

7 Answers 7

255

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);
Sign up to request clarification or add additional context in comments.

6 Comments

Most optimized if you use "LIMIT 1" in your prepare statement.
superbly, please give complete example. Not just a single line that has to go somewhere in the example above.
@andrebruton $dbh = new PDO(" --- connection string --- "); $stmt = $dbh->prepare("SELECT name FROM mytable WHERE id=4 LIMIT 1"); $stmt->execute(); $row = $stmt->fetch();
fetch(PDO::FETCH_ASSOC) will cut the returned array in half if you only need a key-value array.
Do you really need to LIMIT 1 all the time though? Knowing that you're selecting a UNIQUE value comes to mind.
|
19
$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.

Comments

14

Did you try:

$DBH = new PDO( "connection string goes here" );
$row = $DBH->query( "select figure from table1" )->fetch();
echo $row["figure"];
$DBH = null;

1 Comment

You could actually go further and do $row = $DBH->query($query)->fetch()['figure']. If fetch returns false because there are no results, PHP will silently ignore the invalid key reference. If something goes wrong with query, depending on how you've got your error handling set up, it will either throw an Exception (desired, in my opinion) or you'll get an Invalid object method reference "fetch" on "false".... error, a form of which you would have gotten anyway because the query obviously failed.
12

You could try this for a database SELECT query based on user input using PDO:

$param = $_GET['username'];

$query=$dbh->prepare("SELECT secret FROM users WHERE username=:param");
$query->bindParam(':param', $param);
$query->execute();

$result = $query -> fetch();

print_r($result);

1 Comment

I think you are just having a bad day bro, or ur just looking to standout your profile. My answer corroborates with the same scenario using a variable for the SELECT function with a PDO query. I will delete the sql injection comment from my answer just to make your day (and mine).
11

If you want just a single field, you could use fetchColumn instead of fetch - http://www.php.net/manual/en/pdostatement.fetchcolumn.php

Comments

9

how about using limit 0,1 for mysql optimisation

and about your code:

$DBH = new PDO( "connection string goes here" );

$STH - $DBH -> prepare( "select figure from table1" );

$STH -> execute();

$result = $STH ->fetch(PDO::FETCH_ASSOC)

echo $result["figure"];

$DBH = null;

Comments

4

Thanks to Steven's suggestion to use fetchColumn, here's my recommendation to cut short one line from your code.

$DBH = new PDO( "connection string goes here" );
$STH = $DBH->query( "select figure from table1" );
$result = $STH->fetchColumn();
echo $result;
$DBH = null;

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.