-2

I want to select rows from table "students" where username=name from php file. How I can print the rows returned ?? I used this but the values not printed (no results appears )

$result=mysql_query("select name from students where name=$name);


if($result){

while($row=mysql_fetch_array($result))
{
echo " $row['name'];
}
}
Calm Sea
  • 181
  • 2
  • 4
  • 15

4 Answers4

3

If $name is not numeric, MySQL will think it is a column and the column probably does not exist so you will get an error because of that. Put quotes around it like '$name'. You should also call mysql_real_escape_string on $name first, and you should check that the result of mysql_query is not false (if it is, check mysql_error).

You're also missing some quotes.


Even better, stop using ext/mysql and use PDO instead. Then you can write the query like

select name from students where name = ?

and the escaping and quote additions are done automatically for you.

Explosion Pills
  • 188,624
  • 52
  • 326
  • 405
1

if you use string use quote other wise it will treat as column name

$result=mysql_query("select name from students where name='$name'");

Note

  1. The entire ext/mysql PHP extension, which provides all functions named with the prefix mysql_, is officially deprecated as of PHP v5.5.0 and will be removed in the future. So use either PDO or MySQLi

Good read

  1. The mysql extension is deprecated and will be removed in the future: use mysqli or PDO instead
  2. PDO Tutorial for MySQL Developers
  3. Pdo Tutorial For Beginners
Community
  • 1
  • 1
NullPoiиteя
  • 56,591
  • 22
  • 125
  • 143
0

Try:

$result=mysql_query("select name from students where name='$name'");

And echo " $row['name']; should be echo $row['name'];

SeanWM
  • 16,789
  • 7
  • 51
  • 83
0
$result = mysql_query("select name from students where name='$name'");


if($result){

  while($row = mysql_fetch_array($result))
  {
    echo $row['name'];
  }
}
Mihai Matei
  • 24,166
  • 5
  • 32
  • 50