m7m
m7m

Reputation: 49

php with SQL query

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?

Upvotes: 1

Views: 139

Answers (4)

John Parker
John Parker

Reputation: 54445

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.

Upvotes: 5

bensiu
bensiu

Reputation: 25604

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

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

Upvotes: 0

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.

Upvotes: 1

emco
emco

Reputation: 4719

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;

Upvotes: 0

Related Questions