似乎找不到答案,但想知道以下数据库查询是否易受SQL注入攻击。

$searchPostResults = $wpdb->get_results($querySearchVals, OBJECT);

这是使用的查询:
global $wpdb;
$offset = (isset($_POST["moreSearchResults"])) ? $_POST["searchOffset"] : 0;

$querySearchVals = "
    SELECT DISTINCT post_title, ID
    FROM {$wpdb->prefix}posts
    WHERE (";

$sVals = array();
$sVals = explode(" ", $searchVal);

$lastIndex = intval(count($sVals)) - 1;
$orderByCaseVals = "";
for($i = 0; $i<count($sVals);$i++)
{
    $querySearchVals .= " post_title LIKE '%$sVals[$i]%' ";
    if($i != $lastIndex)
        $querySearchVals .= " OR ";

    $orderByCaseVals .= " WHEN post_title LIKE '%$sVals[$i]%' THEN ($i + 2) ";
}

$querySearchVals .= ")
    AND {$wpdb->prefix}posts.post_type = 'post'
    AND post_status = 'publish'
    ORDER BY CASE
        WHEN post_title LIKE '%$searchVal%' THEN 1
        $orderByCaseVals
    END
    LIMIT $offset, 6;
";

干杯

最佳答案

好吧,正如tadman所解释的,get_结果并不能阻止sql注入攻击。
需要使用prepare函数。
为了防止sql注入,我重新编写了上述代码:

global $wpdb;
$offset = (isset($_POST["moreSearchResults"])) ? $_POST["searchOffset"] : 0;

$querySearchVals = "
    SELECT DISTINCT post_title, ID
    FROM {$wpdb->prefix}posts
    WHERE (";

$sVals = array();
$sVals = explode(" ", $searchVal);

$lastIndex = intval(count($sVals)) - 1;
$orderByCaseVals = "";
for($i = 0; $i<count($sVals);$i++)
{
    $queryPrep = $wpdb->prepare(" post_title LIKE '%%%s%%' ", $wpdb->esc_like( $sVals[$i] ));
    $querySearchVals .= $queryPrep;
    if($i != $lastIndex)
        $querySearchVals .= " OR ";

    $queryPrep = $wpdb->prepare(" WHEN post_title LIKE '%%%s%%' THEN ($i + 2) ", $wpdb->esc_like( $sVals[$i] ));
    $orderByCaseVals .= $queryPrep;
}

$querySearchVals .= ")
    AND {$wpdb->prefix}posts.post_type = 'post'
    AND post_status = 'publish'
    ORDER BY CASE";

$queryPrep = $wpdb->prepare(" WHEN post_title LIKE '%%%s%%' THEN 1 ", $wpdb->esc_like( $searchVal ));
$querySearchVals .= $queryPrep;
$querySearchVals .= "
        $orderByCaseVals
    END
";

$queryPrep = $wpdb->prepare(" LIMIT %d, 12", $offset);
$querySearchVals .= $queryPrep . ";";

关于mysql - 使用WordPress get_results()数据库函数是否会阻止sql注入(inject),我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/46208353/

10-11 05:20