Page 1 of 1

Problem passing variable to like or = query

Posted: Sun Mar 13, 2011 8:27 am
by Phpn00b5
$result = mysql_query("SELECT Id FROM AllItems
WHERE Name ='Boots'") or die(mysql_error());

$row = mysql_fetch_array($result) ;

//echo $row['Id'] Works

$var_1 = $row['Id'] ;

//echo $var_1 ; Works


$result2 = mysql_query("SELECT * FROM AllItemSales WHERE FromId like \"%$var_1%\" " ) or die(mysql_error());


$row2 = mysql_fetch_array($result2) or die(mysql_error());

echo $row2 or die(mysql_error()); // Should echo 00000361 but instead outputs 1. Tried with both $row2 and $row2['Id']

If I run the command on PhpMyAdmin (var_1 replaced with its value) I get correct result. I assume I'm doing something wrong here with the use of $var_1 in the Like command(tried with = command to and had same problem)

Any help or advice welcome

Re: Problem passing variable to like or = query

Posted: Sun Mar 13, 2011 12:34 pm
by Asperon
perhaps you need to wrap the variable in curly brackets, sometimes certain symbols in the surrounding string can cause problems when echoing a string in double quotes. you can also use the curly brackets for array echos such as echo "My name is {$person['name']}";

$result2 = mysql_query("SELECT * FROM AllItemSales WHERE FromId like \"%{$var_1}%\" " ) or die(mysql_error());

Or you can do traditional concatenation:

$result2 = mysql_query("SELECT * FROM AllItemSales WHERE FromId like \"%".$var_1."%\" " ) or die(mysql_error());