Forum Moderators: coopster

Message Too Old, No Replies

variable in sql query returns unexpected t_variable

sql query unexpected t_variable

         

huds

4:53 pm on Jun 11, 2005 (gmt 0)

10+ Year Member



I've searched the forums but can't find anything that explains this.

This is a piece of recurring code that is supposed to pass the name of the current page to a variable, and then echo content from a corresponding value in the database.
All it gives me is an 'unexpected T_VARIABLE' error in the line where $textinfo is declared.

// The filename and sql search bit

$filename = ".." . $_SERVER["REQUEST_URI"];

$textinfo = 'SELECT * FROM menu WHERE `menu`.`sitelinks` = $filename LIMIT 0, 30';

$result = mysql_query($textinfo) or die('Query failed: ' . mysql_error());

$pagetext = mysql_fetch_assoc($result);

// Print text

$main_text = $pagetext['maintext'];
echo "$main_text";

// Test variable

echo "$filename";

If I change the...
$textinfo = 'SELECT * FROM menu WHERE `menu`.`sitelinks` = $filename LIMIT 0, 30';

to...
'menu'.'sitelinks' = "$filename"

then it just gives me a blank result.

The test variable returns correctly all the time.

Can anyone help please?

RonPK

5:43 pm on Jun 11, 2005 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member



try this:
"SELECT * FROM menu WHERE `menu`.`sitelinks` = '$filename' LIMIT 0, 30";

* Allways quote strings inside a query: '$filename'
* PHP only parses variables within " and ", not between ' and '.
* in a query string, ` and ' have different meanings. ` is used to indicate table and column names.

mcibor

8:51 pm on Jun 11, 2005 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member



the problem is that you started the string with single quote and then wanted to write single quote, which ended string:

$textinfo = 'SELECT * FROM menu WHERE `menu`.`sitelinks` = $filename LIMIT 0, 30';
menu is undefined: you have string menu, what doesn't mean anything to php. Also in mysql query you should put quotes in data, not table/field name . BTW if you select FROM menu, then you can just write WHERE sitelinks='' .
To correct this you can do is what RonPK said. Use double quotes:

$textinfo = "SELECT * FROM menu WHERE menu.sitelinks='$filename' LIMIT 0, 30";

or print the ' into string with \':

$textinfo = 'SELECT * FROM menu WHERE menu.sitelinks=\'$filename\' LIMIT 0, 30';

Best regards
Michal Cibor

huds

9:40 pm on Jun 11, 2005 (gmt 0)

10+ Year Member



Thanks to both of you.

I've just started learning php, and know nothing about syntax or conventions yet, so your help is much appreciated.