Mark Biwojno
Mark Biwojno

Reputation: 75

Grouping multiple like statements

I'm new to SQL can't seem to group multiple LIKE statements together. Any idea what I am doing incorrectly?

$query = mysqli_query($mysqli, "SELECT * FROM table_name
            WHERE Page LIKE ".$page."
            AND Profession LIKE ".$profession.", 
            AND Age LIKE ".$age."");

Thanks.

Upvotes: 0

Views: 193

Answers (2)

exussum
exussum

Reputation: 18550

Its likely because they are not enclosed correctly

$query = mysqli_query($mysqli, "SELECT * FROM table_name
            WHERE Page LIKE ".$page."
            AND Profession LIKE ".$profession."
            AND Age LIKE ".$age."");

when compiled is something like

SELECT * FROM table_name
            WHERE Page LIKE page number 1
            AND Profession LIKE my profession
            AND Age LIKE 100

which is invalid SQL

You need to use quotes and escape the values

$query = mysqli_query($mysqli, "SELECT * FROM table_name
            WHERE Page LIKE '%".$page."%'
            AND Profession LIKE '%".$profession."%'
            AND Age LIKE '%".$age."%'");

would give

SELECT * FROM table_name
            WHERE Page LIKE '%page number 1%'
            AND Profession LIKE '%my profession%'
            AND Age LIKE '%100%'

Which will likely give a result of what you would expect

Make sure the values are safe though by at bare minimum using http://www.php.net/manual/en/mysqli.real-escape-string.php though looking at prepared statements would be a better option

Edit:

Remove comma after LIKE ". $profession."

Upvotes: 1

tadman
tadman

Reputation: 211540

This would be a lot easier to get right if you use placeholders and bind_param:

$stmt = mysqli_query($mysqli, "SELECT * FROM table_name
            WHERE Page LIKE ?
            AND Profession LIKE ?
            AND Age=?");

mysqli_stmt_bind_param($stmt, 'ssi', "%" . $page . "%", "%" . $profession. "%", $age);

mysqli_stmt_execute($stmt);

Upvotes: 0

Related Questions