Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Return One Row from MySQL

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?
like image 527
user1114864 Avatar asked Jul 02 '12 23:07

user1114864


3 Answers

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"]; 
like image 78
mgraph Avatar answered Sep 23 '22 16:09

mgraph


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.

like image 23
gcochard Avatar answered Sep 21 '22 16:09

gcochard


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 );
like image 31
Daniel Aranda Avatar answered Sep 20 '22 16:09

Daniel Aranda