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?
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"];
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
.
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 );
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With