Forum Moderators: coopster

Message Too Old, No Replies

Passing a variable from a form to a MySql query

It's got to be something simple (I hope)

         

ianking

5:06 pm on Apr 7, 2005 (gmt 0)

10+ Year Member



I have a form set up with a dropdown list of values for a field "Genre" in my database

I can pass the variable to my php script. I know this because I use:

$Genre = $_POST['Genre'];

echo "<h1> Query result for Genre = ","$Genre", "</h1>";

And the page prints the appropriate value chosen from the form.

I'm trying to use the $Genre variable in a mysql query to select records which match.

My mysql query works when I use the following code:

$sql = 'SELECT `reviews`. `ID`,`reviews`.`Title`, `reviews`.`Author`, `reviews`.`Genre`, `reviews`.`Theme`, `reviews`.`Rating`,`reviews`.`Review`,`reviews`.`Reviewer`, `reviews`.`Class`, `reviews`.`pic`'. ' FROM reviews'. ' WHERE (`reviews`.`Genre` like "Science Fiction" )'. ' ORDER BY `reviews`.`Title` ASC LIMIT 0, 30';

but not when I substitute "Science Fiction" with $Genre

Anyone got any ideas - I've been trying all sorts of possibilities including using $_POST['Genre'] again but to no avail.

The error I get is:

Warning: mysql_fetch_row(): supplied argument is not a valid MySQL result resource in c:\Inetpub\wwwroot\newphptut\query2.php on line 20

Many thanks for any help you can give.

Ian

volatilegx

5:30 pm on Apr 7, 2005 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member



Welcome to WebmasterWorld :)

Try this:

$sql = 'SELECT `reviews`. `ID`,`reviews`.`Title`, `reviews`.`Author`, `reviews`.`Genre`, `reviews`.`Theme`, `reviews`.`Rating`,`reviews`.`Review`,`reviews`.`Reviewer`, `reviews`.`Class`, `reviews`.`pic`'. ' FROM reviews'. ' WHERE (`reviews`.`Genre` like "'.addslashes($Genre).'" )'. ' ORDER BY `reviews`.`Title` ASC LIMIT 0, 30';

ianking

6:37 pm on Apr 7, 2005 (gmt 0)

10+ Year Member



Worked a treat - you are a gem.

Could you possibly explain what I was doing wrong - what does addslashes do?

Thanks again for the speedy reply

Ian

coopster

12:35 am on Apr 8, 2005 (gmt 0)

WebmasterWorld Administrator 10+ Year Member



addslashes() [php.net] returns a string with backslashes before characters that need to be quoted in database queries.

The issue you had was that you need to have quotation marks around the value in your LIKE predicate -- so when you

substitute "Science Fiction" with $Genre

you still need to keep the quotation marks around $Genre.