简体   繁体   English

如何在PHP中缩写MySQL查询?

[英]How to abbreviate MySQL queries in PHP?

I have a page that needs to make six nearly identical queries with the only difference between them being the value of "category": 我有一个页面,需要进行六个几乎相同的查询,它们之间的唯一区别是“类别”的值:

$query = "SELECT * FROM table_name WHERE category="CATEGORY1";

Instead of writing out six different $query variables ($query1, $query2, etc.) for each different category, I'd like to abbreviate so I can pass in category as a variable each time I instantiate $query, like so: 我不想为每个不同的类别写出六个不同的$ query变量($ query1,$ query2等),而是想简化一下,以便每次实例化$ query时都可以将类别作为变量传递,如下所示:

$query = "SELECT * FROM table_name WHERE category='$cat'";
$results= mysql_query($query,'CATEGORY1');

There must be some way to do this, but I simply can't find the syntax anywhere for passing a variable to a MySQL query in this way (I checked php.net, this site, various other php resources on Google). 一定有某种方法可以做到这一点,但是我根本找不到任何以这种方式将变量传递给MySQL查询的语法(我检查了php.net,该站点以及Google上的各种其他php资源)。 Can anyone help me out? 谁能帮我吗?

Much appreciated, thanks! 非常感谢,谢谢!

Use PDO and prepared statements 使用PDO准备好的语句

$categories = array(
    'CATEGORY1',
    'CATEGORY2',
    'CATEGORY3',
    'CATEGORY4',
    'CATEGORY5',
    'CATEGORY6'
);

$db = new PDO(...);
$stmt = $db->prepare('SELECT * FROM table_name WHERE category = :category');
$stmt->bindParam('category', $category);
foreach ($categories as $category) {
    $stmt->execute();
    while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
        // do stuff with $row
    }
}

You can't use a single variable in SQL to represent a comma separated list, like I'd use for situations like these as values for an IN clause. 您不能在SQL中使用单个变量来表示逗号分隔的列表,就像我在这种情况下将它们用作IN子句的值一样。 You need to use dynamic SQL, which means constructing the query as a string before submitting it to the database. 您需要使用动态SQL,这意味着在将查询提交到数据库之前将其构造为字符串。

$array = array('category1', 'category2', 'category3');
$comma_separated = implode("','", $array);

$query = "SELECT * 
            FROM table_name 
           WHERE category IN ('$comma_separated')";

$results = mysql_query($query);

An alternative would be to use MySQL's Prepared Statement syntax , which is MySQL's dynamic SQL syntax... 一种替代方法是使用MySQL的Prepared Statement语法 ,这是MySQL的动态SQL语法...

You can use sprintf for that: 您可以为此使用sprintf

$query = "SELECT * FROM table_name WHERE category='%s'";
$results= mysql_query(sprintf($query,'CATEGORY1'));

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

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