ARTICLE AD BOX
Just fetch. only gets one row. So no foreach loop needed :D
$row = $stmt->fetch();example
$id = 4; $stmt = $dbh->prepare("SELECT figure FROM mytable WHERE id=? LIMIT 1"); $stmt->execute([$id]); $row = $stmt->fetch(PDO::FETCH_ASSOC); $figure = $row["figure"];By the way, if you are selecting just one column, you can get its value right with fetch. Useful for getting values like count(*) etc:
$figure = $stmt->fetchColumn();6 Comments
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.
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.
2016-11-01T17:40:43.68Z+00:00
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).
2014-06-12T05:51:16.283Z+00:00
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;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;Explore related questions
See similar questions with these tags.



