0

I have a very noobish question right here. How can I use PHP in my PHP SQL query?

My query is

mysqli_query($GLOBALS["___mysqli_ston"], "SELECT * FROM shop WHERE categorie='4' AND actief='1' ORDER BY prijs + 0 ASC");

and what I'm trying to have is this

mysqli_query($GLOBALS["___mysqli_ston"], "SELECT * FROM shop WHERE categorie='4' AND ". if(htmlentities($gegevens['rang']) == '1') { echo ""; } else { echo "actief='1'";} . " ORDER BY prijs + 0 ASC");

How can I get this to work?

2 Answers 2

1

For everyone's sanity, please do not use ternary conditions inside SQL string concatenation.

$andActeif = "";
if (intval($gegevens['rang']) == 1) {
    $andActive = " AND acteif = '1' ";
}
mysqli_query($GLOBALS["___mysqli_ston"], "
   SELECT * 
   FROM shop
   WHERE categorie='4'
   $andActeif
   ORDER BY prijs + 0 ASC");

Your future self will thank you.

Sign up to request clarification or add additional context in comments.

Comments

0

You need to use the ?: conditional (AKA ternary) expression.

mysqli_query($GLOBALS["___mysqli_ston"], "SELECT * FROM shop WHERE categorie='4' ". ($gegevens['rang'] == '1' ? "" : "AND actief='1'") . " ORDER BY prijs + 0 ASC");

And the AND should be part of the string that's added by the conditional code. Otherwise, when $gegevens['rang'] is not 1, you'll have AND with no condition after it.

For a more general approach to building the WHERE clause dynamically, see

Search Form with One or More (Multiple) Parameters

3 Comments

Hello Barmar, when I'm working with your code it give me an error: "You have an error in your SQL syntax; check the manual that corresponds to your MariaDB server version for the right syntax to use near 'ORDER BY prijs + 0 ASC' at line 1"
The AND should be in the conditional ;)
mysqli_query($GLOBALS["___mysqli_ston"], "SELECT * FROM shop WHERE categorie='4' ". ($gegevens['rang'] == '1' ? "" : " AND actief='1'") . " ORDER BY prijs + 0 ASC");

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.