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?

0

4 Answers 4

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.

Sign up to request clarification or add additional context in comments.

Comments

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.

1 Comment

No, he don't want to use like
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;

Comments

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

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.