使用WordPress get_results()数据库函数是否会阻止sql注入

时间:2017-09-13 23:40:20

标签: mysql wordpress security sql-injection

似乎无法找到答案,但想知道以下对数据库的查询是否容易受到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;
";

干杯

1 个答案:

答案 0 :(得分:1)

好的,所以tadman解释说get_results不会阻止sql注入攻击。

需要使用准备功能。

我已经重写了上面的代码以防止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 . ";";