-1

I am really new at SQL and PHP. Basically I need to store a query result into a variable. I have something like this:

$id = mysql_query("SELECT id FROM users WHERE name = ($user)");

So I want $id to have the value of id from table users where the name field in users table = $user (value of a logged-in user).

May I know how to make this work?

Sorin
  • 5,201
  • 2
  • 18
  • 45
Huang Kai
  • 31
  • 1
  • 3
  • Yo can refer this http://stackoverflow.com/questions/5157905/mysql-query-result-in-php-variable – Shreyas Achar Oct 17 '15 at 07:15
  • In this ase your first step should have been to check the php.net's mysql tutorial http://php.net/manual/en/book.mysql.php – Arpita Oct 17 '15 at 07:35

3 Answers3

0

mysql_query only execute the query. you can not get the results from this. you need mysql_fetch_assoc for fetching the records. and you should put $user in quotes.

check the below code.

$id= mysql_query("SELECT id FROM users WHERE name = '$user'");

while($result = mysql_fetch_assoc($id)){
   print_r($result);
}
urfusion
  • 5,528
  • 5
  • 50
  • 87
0

user mysql_fecth_object: https://secure.php.net/manual/en/function.mysql-fetch-object.php

$query= mysql_query('SELECT id FROM users WHERE name = '"'. mysql_real_escape_string($user) .'"' LIMIT 1);

$result = mysql_fetch_object($query); 
$id = $result->id;

This extension was deprecated in PHP 5.5.0, and it was removed in PHP 7.0.0. You should use MySli or PDO instead

urfusion
  • 5,528
  • 5
  • 50
  • 87
0

When you are executing mysq_query() .you will get a complete data table towards your query.just check one way to find the solution is given below.

$result= mysql_query("SELECT id FROM users WHERE name = '$user'");
if($row=mysql_fetch_array($result)){
  $id=$row['id'];
}
anuraj
  • 157
  • 8