Why wont this work?

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
dominod
Forum Commoner
Posts: 75
Joined: Wed Jun 30, 2010 7:18 am

Why wont this work?

Post by dominod »

Hi

I am having trouble with this code:

Code: Select all

$query = "SELECT * FROM `engines` WHERE name LIKE '$keyword%' AND (languages='$english' OR languages='$lang') ORDER BY hits DESC ";
It is the languages='$lang' that dont work..

$lang =

Code: Select all

'Finnish' OR languages='Italian' OR languages='German'
I think it has something to do with double ' symbols, but I dont know how to solve it :/

Anyone know?

Thanks in advance :)
User avatar
Apollo
Forum Regular
Posts: 794
Joined: Wed Apr 30, 2008 2:34 am

Re: Why wont this work?

Post by Apollo »

Are $keyword and $english defined? (you're using not the string 'english' but the variable $english!) and are you sure the SQL field is called languages? (since you seem to compare it with just one language at a time).

Anyway, if $lang is litterally this:
[text]'Finnish' OR languages='Italian' OR languages='German'[/text]
Then this query: (note the absence of quotes here)

Code: Select all

$query = "SELECT * FROM `engines` WHERE (languages=$lang) ORDER BY hits DESC";
Would evaluate to:
[text]SELECT * FROM `engines` WHERE (languages='Finnish' OR languages='Italian' OR languages='German') ORDER BY hits DESC";[/text]
Which is probably what you need?

This is a REAL bad, risky, error-prone, badly maintainable, vulnerable, crappy approach though :)

I'd highly recommend doing something like this instead: (more code, less headache)

Code: Select all

$languages = array('English','German','French');

$lang = array();
foreach($languages as $s) $lang[] = "languages='".mysql_real_escape_string($s)."'";
$lang = implode(' OR ',$lang);
$query = "SELECT * FROM `engines` WHERE ($lang) ORDER BY hits DESC";
dominod
Forum Commoner
Posts: 75
Joined: Wed Jun 30, 2010 7:18 am

Re: Why wont this work?

Post by dominod »

Its working now! Thanks alot! :D
Post Reply