tags:

views:

34

answers:

4

Whats the best way to print from mysql using php when you know theres only going to be a single record.

My Sql 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 etc

But thats ok for more than one record. Any better way to do this when theres only one?

Thanks

+1  A: 

$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);
}
fredley
Using the function is negligibly slower than just doing `$row = mysql_fetch_assoc(mysql_query($sql));`, but makes your code cleaner, and more error resistant :-)
fredley
+2  A: 

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.

Eton B.
A: 

You can just leave off the while. It will probably make execution a minute bit faster.

sims
+1  A: 

Hello Norman, I hope this help you...

<?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';
    ?>

All the Best !!!

Rahul Patil