jeremy
jeremy

Reputation: 653

use a single return from a sql query

I'm using PHP to make a very specific sql query. For example sake, I have the user's ID number, but I need their name. So I do a sql query from that table with the ID number in order to return the name.

$result = mysql_query("SELECT name FROM users WHERE userID=$thisuserid",$db);

Now I want to use that. What's the most succinct way to go about making that result into a variable ths I can use?

edit: I'm hoping that this is not the answer:

$rowCheck = mysql_num_rows($result);
if ($rowCheck > '0') {
   while ($row = mysql_fetch_assoc($result)){
    foreach ($row as $val){
        $username = $val;
    }
   }
}

Upvotes: 0

Views: 102

Answers (4)

sonnb
sonnb

Reputation: 408

You should use MySQLi as bellow:

$db = new MySQLi($host,$user,$pass,$db);
$query = $db->query('SELECT name FROM users WHERE userID='.$thisuserid);
$result = $query->fetch_object();
echo $result->name;

If you use SELECT * so you also can access via $result->{field_name}

Upvotes: 0

user747858
user747858

Reputation:

$result = mysql_query("SELECT name FROM users WHERE userID=$thisuserid",$db);

if (!$result) {
  echo 'Could not run query: ' . mysql_error();
  exit;
}
$name = mysql_fetch_row($result)[0];

Upvotes: 0

Misguided
Misguided

Reputation: 1312

In my opinion, the best way to fetch any SQL result is through mysql_fetch_assoc(). To use it, you would do something like this:

$result = mysql_query("SELECT name FROM users WHERE userID=$thisuserid",$db);

while ($row = mysql_fetch_assoc($result)) {
    echo $row['name']; // You get an array with each column returned from your query.
}

Still, MySQL extension has been replaced for MySQLi, which is acknowledged to be faster and more practical. It has both OOP and structural bindings, and takes more into account your server settings.

Upvotes: 0

Sabeen Malik
Sabeen Malik

Reputation: 10880

I have used something like this to keep it short in the past:

list($name) = mysql_fetch_row(mysql_query("SELECT name FROM users WHERE userID=$thisuserid",$db));
echo $name;

Upvotes: 2

Related Questions