Forum Moderators: coopster

Message Too Old, No Replies

String literals in mysql queries

         

nickknowledge

12:46 pm on Aug 15, 2005 (gmt 0)

10+ Year Member



SQL queries which were working fine now have stopped working if I store them in a mysql TEXT field.

So:

$sql_student = "SELECT s.student_user_id, u.user_firstname, u.user_lastname from students as s JOIN users as u ON u.ID = s.student_user_id WHERE s.student_id = '$student_id'";

$student = $ez->get_row($sql_student);

Becomes:

$sql_report_sql = "select report_sql from report_styles where report_style_id = '$report_style'";

$sql_student = $ez->get_var($sql_report_sql);

$student = $ez->get_row($sql_student);

If I echo $sql_student to the screen, it's:

SELECT s.student_user_id, u.user_firstname, u.user_lastname from students as s JOIN users as u ON u.ID = s.student_user_id WHERE s.student_id = '$student_id'

But when I run the statement, '$student_id' is not interpreted, and the query fails.

Do I need to do some kind of string replace, or escape with backslashes?

I've tried using curly braces around $student_id, and single / double quote combinations, including with backslashes. Am lost.

I'm using the ezsql class.

Thanks for any help.

mcibor

12:53 pm on Aug 15, 2005 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member



It's not working because it's a text, not variable.
You would have to execute it, but better is str_replace:

$sql_student = "SELECT s.student_user_id, u.user_firstname, u.user_lastname from students as s JOIN users as u ON u.ID = s.student_user_id WHERE s.student_id = '$student_id'";
$sql_student = str_replace('$student_id', $student_id, $sql_student);
$student = $ez->get_var($sql_student);

This should be working now.
'$student_id' is a text, not variable, so you replace it with $student_id, which is a variable.
Hope this cleares things!
Best regards
Michal Cibor

PS. There's another method to do it, but this one is the most secure.