Reputation: 6365
What's the best way to print from MySQL using PHP when you know there's only going to be a single record?
My SQL statement is:
select user from users where user = 'norman';
This will return only a single record. So what's the best way to print it? I currently do:
while ($info=mysql_fetch_assoc($data))
etc
But that's OK for more than one record. Any better way to do this when there's only one?
Upvotes: 0
Views: 691
Reputation: 6542
Try this:
<?php
include 'config.php';
include 'opendb.php';
$query = "select user from users where user = 'norman";
$result = mysql_query($query);
while($row = mysql_fetch_array($result))
{
echo "Name :{$row['user']}";
}
include 'closedb.php';
?>
Upvotes: 1
Reputation: 6773
You can just leave off the while. It will probably make execution a minute bit faster.
Upvotes: 0
Reputation: 6281
If you're absolutely certain that this query will always retrieve 1 row then this should be enough:
$row = mysql_fetch_assoc(mysql_query($sql));
Then you can manipulate $row (the single row) at your will.
Upvotes: 4
Reputation: 33911
$row = mysql_fetch_assoc(mysql_query($sql));
then do what you want:
echo $row['value'];
You need to know in advance that this is going to return a single row. You could use a function:
function fetch_single_row($sql){
$result = mysql_query($sql);
if (mysql_num_rows($result) > 1){
return false;
}
return mysql_fetch_assoc($result);
}
Upvotes: 1