php - 尝试将 for i+ 放入 mysql 查询、php wordpress 中

标签 php mysql arrays wordpress pdo

你们有什么方法可以将 for i+ 放入 mysql 查询中,或者有什么方法可以使字符串取决于数组的数量?

我必须这样做的原因是因为我使用 wordpress 并且我必须使用 IN() 来内爆一个数组。不幸的是,如果我必须使用 $wpdb->prepare,并且我需要使用 %s,如果我使用 %s,我的字符串必须与 %s 匹配。当然,我可以使用 foreach,但是如果我的数组有一百次值,那么查询将被调用一百次。而且,如果我不使用 $wpdb->prepare,我也没有问题,但它不安全。

我本来想PDO,但是我对PDO不太熟悉,我认为$wpdb->prepare比PDO更安全。所以,我在这里感到震惊。试图找出一种根据数组数量动态创建字符串的方法。

任何想法,感激不尽。

<?php

$arg = array('a','b','c');//i don't use foreach because my array is so long that will call query hundred times.

$t= implode(',', array_fill(0, count($arg),'%s'));
$sym = $wpdb->get_results( $wpdb->prepare("
SELECT DISTINCT disease FROM dis WHERE disease IN ($t)
" ,for( $i= 0 ; $i <= count($arg); $i++ )
{
echo $arg[$i];
}));


?>

最佳答案

我知道您出于安全原因尝试使用 $wpdb->prepare 但我认为 $wpdb->prepare 不适合您的情况。您正在创建一个大型查询字符串,并且此函数似乎存在问题。 wordpress 文档指出 $wpdb->prepare 并不适合所有情况。让我们寻找替代方案,同时确保它对于我们的查询足够安全。如果我们浏览 esq_sql doc

In 99% of cases, you can use $wpdb->prepare() instead, and that is the recommended method. This function is only for use in those rare cases where you can't easily use $wpdb->prepare().

我认为我们遇到了这些罕见的情况之一,我们不能轻易使用 $wpdb->prepare()

Note: Be careful to use this function correctly. It will only escape values to be used in strings in the query. That is, it only provides escaping for values that will be within quotes in the SQL (as in field = '{$escaped_value}').

并且我们的值在引号内,因此我们满足此条件

If your value is not going to be within quotes, your code will still be vulnerable to SQL injection. For example, this is vulnerable, because the escaped value is not surrounded by quotes in the SQL query: ORDER BY {$escaped_value}. As such, this function does not escape unquoted numeric values, field names, or SQL keywords.

这个警告不适用于我们的情况。

出于这些原因,我认为您可以在您的情况下使用 esq_sql 而不会影响安全性。像这样的东西应该有效:

<?php
$arg = array( 'a', 'b', 'c' );
$arg_str = " ";

foreach ( $arg as $val ) {
    $arg_str .= "'" . esc_sql( $val ) ."', ";
}
// Remove the last comma
$arg_str = substr ( $arg_str, 0, strlen( $arg_str ) - 2 );

$result = $wpdb->get_results( "SELECT DISTINCT disease FROM dis 
                               WHERE disease IN ( " . $arg_str . " )" );

?>

关于php - 尝试将 for i+ 放入 mysql 查询、php wordpress 中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38751283/

相关文章:

php - 使用 codeception 测试多个 url(文件)并记录单独的结果

javascript - 如何为 Bootstraps 模态传递数据

php - 运行composer update后出现查询异常

mysql - SQL SELECT(多-2-多)

php - 阻止 Internet Explorer 提供保存/下载文件的选项

php - 制作一个php库,如何使其独立?

php - 查找 sql 值最新变化的更好方法

javascript - 现代浏览器如何实现 JS Array,具体是添加元素?

c++ - 字符数组中的线性搜索——C++ (Visual Studio 2005)

c - 将结构数组传递给函数作为输入