0

I'm calling a table from mySQL database using PDO as you can see :

$reponse = $bdd->query('SELECT * FROM exercices WHERE chapitre=\'hello\' ORDER BY id DESC');

Now, I want to do the same thing but instead of 'hello' I would like to use a variable set before like that :

$reponse = $bdd->query('SELECT * FROM exercices WHERE chapitre=\'echo $cat\' ORDER BY id DESC');

It doesn't work. I may have a problem with "echo $cat". Somebody knows ? Thanks.

1
  • in sql queries you do not echo variables. You use them directly. Commented Jan 3, 2016 at 16:21

4 Answers 4

1

Use binded variables, I don`t know where the variable is coming from but to be safe:

$reponse = $bdd->query('SELECT * FROM exercices WHERE chapitre=:cat ORDER BY id DESC');
$reponse->bindParam(':cat', $cat, PDO::PARAM_STR); //assuming it is a string
$reponse->execute();
$result = $reponse->fetchAll(); //make the select
print_r($result);  //debug
Sign up to request clarification or add additional context in comments.

2 Comments

You just beat me to the punch haha. Nice answer :)
Hehe, happens to me allot too :P
0

your query can be:

$reponse = $bdd->query('SELECT * FROM exercices WHERE 
chapitre=\''.$cat.'\' ORDER BY id DESC');

you should understand the difference between "" and '', also you can " in 2 single quota without any problem and vice versa. if you want write " in 2 double quota you should use \ also the same when you write ' in 2 single quota.

Comments

0

The way I do a query like that is this:

$cat = $_POST['cat'];
$response = $bdd->prepare("SELECT * FROM exercices WHERE chapitre= :cat ORDER BY id DESC");
$response->bindParam(':cat', $cat,PDO::PARAM_STR);
$response->execute();

I like this the best as it's clean and easy to understand.

Comments

0

You do not need to echo the variable when passing it as argument. Wrap the whole string in double quotes and place the variable. Double quotes strings are parsed by PHP to place the variable values in string.

Use it in this way

$reponse = $bdd->query("SELECT * FROM exercices WHERE chapitre= '$cat' ORDER BY id DESC");

Comments

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.