-2

I have the following problem:
I am trying to select a result from a MySQL database table, depending on the category value:

$sql = mysql_query("SELECT * FROM products WHERE category='garniture' ORDER BY date_added DESC LIMIT 2");   

The problem is that I don't want to use a static value for category (like 'garniture'), but I want this to be determined by a variable value (let's say that variable is $category). How can I manage this?

0

2 Answers 2

1

Without getting into the fact that you should not be using the MySQL Library anymore, use MySQLi or PDO instead, you would insert a variable in that string as such:

$sql = mysql_query("SELECT * FROM products WHERE category='$category' ORDER BY date_added DESC LIMIT 2");

Or if you find it easier to read:

$sql = mysql_query("SELECT * FROM products WHERE category='" . $category . "' ORDER BY date_added DESC LIMIT 2");
Sign up to request clarification or add additional context in comments.

5 Comments

Thanks, this works nicely.
you told the OP to not use mysql_ library and then proceeded to do so; it might be better if you showed how to do it the correct way instead of encouraging bad habits. In fact your answer leaves the OP wide open to SQL injection. I would not recommend this approach at all
@nomistic -- You don't know where the variable is coming from. So to its wide open to injection is a statement backed by no facts.
@dlporter98 If a nefarious user discovers that a variable is being included within a query, like $category it can easily be manipulated. It's better to use prepared statements, however in this case, this variable is not even being escaped. Note that Madness understands this with the reference to PDO or mysqli. I was just suggesting it would be better to show the OP the safer way
The real question was "how to join a variable in a string". Bad wording yes, but he had a question and I had an answer. A full example of proper MySQLi or PDO is WAY beyond the scope of answering this question. And rather than get in an argument, I stated I WAS NOT GOING TO GET INTO IT HERE, but gave him the information so he could look it up himself. This issue has been resolved for the OP, everyone have a nice day moving on to HELP other SO users.
1
$sql = mysql_query("SELECT * FROM products WHERE category='$category' ORDER BY date_added DESC LIMIT 2");

Just put the variable where you want it in the string.

The most important feature of double-quoted strings is the fact that variable names will be expanded. See string parsing for details.

See the PHP manual about string interpolation.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.