简体   繁体   English

PHP:变量到SQL查询(PDO)

[英]Php : variable into SQL QUERY (PDO)

I'm calling a table from mySQL database using PDO as you can see : 如您所见,我正在使用PDO从mySQL数据库调用表:

$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 : 现在,我想做同样的事情,但是我想使用一个变量集代替“ hello”:

$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". 我可能对“ echo $ cat”有疑问。 Somebody knows ? 有人知道吗? Thanks. 谢谢。

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

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. PHP对双引号字符串进行了解析,以将变量值放入字符串中。

Use it in this way 以这种方式使用

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

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. 您应该了解“”和“”之间的区别,也可以在“ 2个单配额”中没有任何问题,反之亦然。如果您想在“ 2个双配额”中写入“,则应该在两个单配额中写入\\配额。

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. 我最喜欢它,因为它干净而且易于理解。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM