Return One Row from MySQL
34,138
Solution 1
Add limit 0,1
and for PHP 7 use mysqli
$query = "SELECT name,age FROM people WHERE uid = '2' LIMIT 0,1";
$result = mysqli_query($query);
$res = mysqli_fetch_assoc($result);
echo $res["age"];
Solution 2
If uid
is your primary key, or it has a unique
constraint, you can simply call mysql_fetch_row($res)
once.
If you want to verify that you actually got a result, you can check if mysql_num_rows($res) == 1
.
Solution 3
There is not any loop required, just call the function to extract one row from a Query Resultset:
$query = "SELECT name,age FROM people WHERE uid = '2'";
$result = mysql_query($query);
$row = mysql_fetch_assoc( $result );
var_dump( $row );
Author by
user1114864
Updated on October 05, 2020Comments
-
user1114864 over 3 years
Amateur question, but something I've been wondering about. What is the PHP for selecting one row from a MySQL query? AKA you're picking something by unique ID (you know there's only one row that matches your request) and want to get only that value. Do you still have to use a while loop and mysql_fetch_row?
$query = "SELECT name,age FROM people WHERE uid = '2'"; $result = mysql_query($query); // what php is used to return the name and age? preferably without a loop?