1

i have a problem with php in the following:

$sql = 'SELECT name FROM chiled WHERE `im` LIKE $id ';
$query = mysql_query( $sql );
$a=mysql_fetch_row($query);
echo $a[0]; 

there is error in mysql_fetch_row($query); but if i do the following :

$sql = 'SELECT name FROM chiled WHERE `im` LIKE 1111 ';
$query = mysql_query( $sql );
$a=mysql_fetch_row($query);
echo $a[0];

it is working and prints the name can you please tell me what is wrong?

ThiefMaster
  • 310,957
  • 84
  • 592
  • 636
m7m
  • 49
  • 2
  • 6

4 Answers4

5

Single quotes in PHP doesn't evaluate embedded variables - you need to use double quotes to do that. (See the "Single quoted" section of the PHP Strings manual page for more info..)

i.e.: $sql = "SELECT name FROM chiled WHERE 'im' LIKE $id ";

Or better still...

$sql = 'SELECT name FROM chiled WHERE im="' . mysql_real_escape_string($id) . '"';

(As you're not using the % in your like, you're presumably not attempting to do any form of pattern matching.)

Additionally, I'd recommend a read of the existing Best way to stop SQL Injection in PHP question/answers.

Community
  • 1
  • 1
John Parker
  • 54,048
  • 11
  • 129
  • 129
1

Are you sure you want to be using LIKE? It looks more to me like you want to see if im = $id. Also, make sure you're escaping your variables before using them in the query.

Edit
If you DO want to us LIKE, you probably want something like this:

$sql = "SELECT name FROM chiled WHERE `im` LIKE '%$id%' ";

which will find anywhere that the string $id is found in the im column.

0

You need to quote the variable after LIKE, like this:

$sql = "SELECT name FROM chiled WHERE im LIKE '$id'";
$query = mysql_query($sql); 
$a = mysql_fetch_row($query); 
echo $a[0]; 
// ....

Beside, you are using single quotes, Therefore, $id is not replaced for its value. Your query look like this: SELECT name FROM chiled WHERE im LIKE $id;

emco
  • 4,589
  • 3
  • 18
  • 20
0
$sql = "SELECT name FROM chiled WHERE `im` LIKE '$id' ";

change to double quotes - http://php.net/manual/en/language.types.string.php

bensiu
  • 24,660
  • 56
  • 77
  • 117