举例说明如何参数化sql查询以防止sql注入攻击

时间:2013-08-17 03:43:26

标签: php mysql prepared-statement sql-injection

这是参数化之前的SQL查询。我试图参数化代码以防止SQL注入攻击。 Bansi帮助我完成了这项工作。他的回答如下:

以下代码是我们要参数化的内容。

$sqlCommand = "(SELECT * FROM products WHERE product_name LIKE '%$searchquery%' OR details LIKE '%$searchquery%' OR category LIKE '%searchquery%' OR subcategory LIKE '%searchquery%' OR price LIKE '%searchquery%') ";
} 
require_once("storescripts/connect_to_mysqli.php");
$query = mysqli_query($myConnection,$sqlCommand) or die(mysqli_error($myConnection));
$count = mysqli_num_rows($query);
if($count >= 1){
    $search_output .= "<hr />$count results for <strong>$searchquery</strong><hr />";
    while($row = mysqli_fetch_array($query)){

根据bansi答案,它应该更改为下面的代码。关键部分如下

require_once ("storescripts/connect_to_mysqli.php");
$stmt = $myConnection->prepare('SELECT id, product_name, price FROM products WHERE product_name LIKE ? OR details LIKE ? OR category LIKE ? OR subcategory LIKE ? OR price LIKE ?');
$param = "%$searchquery%";
$stmt->bind_param('sssss', $param, $param, $param, $param, $param);
$stmt->execute();
/* store result */
$stmt->store_result();
/* get the row count */
$count = $stmt->num_rows;
if ($count >= 1) {
    $search_output = "<hr />$count results for <strong>$searchquery</strong><hr />";
    $stmt->bind_result($id, $product_name, $price);

    while ($stmt->fetch()) {
        printf("%s %s %s\n", $id, $product_name, $price);

3 个答案:

答案 0 :(得分:2)

问题在于准备好的声明中的引文。 正确的方法是在引号周围省略单引号。如果您需要在引号内使用引号,则可以在单引号中使用双引号。

以下是解决方案:

  

$ stmt = $ myConnection-&gt; prepare('SELECT * FROM products WHERE product_name LIKE?OR details LIKE?OR category LIKE?OR subcategory LIKE?OR price LIKE?');

制作字符串时的另一个选择是将字符串与。连接起来。像这样:

  

$ string = $ oldString。 “你好”;

答案 1 :(得分:1)

您的第一个问题是您没有正确参数查询。你过早地终止了你的字符串并从语言解释器的上下文中插入了?。这显然会导致语法错误。

插入参数而不破坏字符串。

->prepare('SELECT * FROM products WHERE product_name LIKE ? OR details LIKE ? OR category` LIKE ? OR subcategory LIKE ? OR price LIKE ?');

现在你有5个参数。您需要为所有5个参数提供值,如下所示。

$stmt->bind_param('sssss', "%$searchquery%", "%$searchquery%", "%$searchquery%", "%$searchquery%", "%$searchquery%");

我还注意到您在'变量中使用过单引号(%$searchquery%)。您需要使用双引号",因为单引号不会扩展您的变量。

答案 2 :(得分:1)

下面的代码可以运行并给你结果,但它没有正确显示结果 如何修改$ search_output?

<?php

$search_output = "";

if (isset($_POST['searchquery']) && $_POST['searchquery'] != "") {
    $searchquery = preg_replace('/[^a-zA-Z0-9_ %\[\]\/\.\(\)%&-]/s', '', $_POST['searchquery']);
    if ($_POST['filter1'] == "Products") {
        require_once ("storescripts/connect_to_mysqli.php");
        //syntax error string not quoted properly
        $stmt = $myConnection->prepare('SELECT * FROM products WHERE product_name LIKE ? OR details LIKE ? OR category LIKE ? OR subcategory LIKE ? OR price LIKE ?');
        $param = "%$searchquery%";
        $stmt->bind_param('sssss', $param , $param , $param , $param , $param);
        $stmt->execute();
        $stmt->bind_result($id, $product_name, $price);

        while ($stmt->fetch()) {
            printf("%s %s %s\n", $id, $product_name, $price);
            $search_output .= "
            <li><div class='product'>
            <a href='product.php?id=$id' class='info'>
            <span class='holder'>
            <img src='inventory_images/$id.jpg' alt='$product_name' />
            <span class='book-name'>$product_name</span>
            </a>
             <a href='product.php?id=$id' class='buy-btn'>RM<span class='price'>$price</span></a>
            </div>
            </li>

            ";
        }//While loop was not closed

    } else {
        $search_output = "<hr />0 results for <strong>$searchquery</strong><hr />";
    }
}
?>

您有2个语法错误。 编辑修复绑定语句并更改了sql

<?php

$search_output = "";

if (isset($_POST['searchquery']) && $_POST['searchquery'] != "") {
    $searchquery = preg_replace('/[^a-zA-Z0-9_ %\[\]\/\.\(\)%&-]/s', '', $_POST['searchquery']);
    if ($_POST['filter1'] == "Products") {
        require_once ("storescripts/connect_to_mysqli.php");
        //syntax error string not quoted properly
        $stmt = $myConnection->prepare('SELECT * FROM products WHERE product_name LIKE ? OR details LIKE ? OR category LIKE ? OR subcategory LIKE ? OR price LIKE ?');
        $param = "%$searchquery%";
        $stmt->bind_param('sssss', $param , $param , $param , $param , $param);
        $stmt->execute();
        $stmt->bind_result($product_name, $price);

        while ($stmt->fetch()) {
            printf("%s %s\n", $product_name, $price, $totalpoints);

            $search_output .= "
            <li><div class='product'>
            <a href='product.php?id=$id' class='info'>
            <span class='holder'>
            <img src='inventory_images/$id.jpg' alt='$product_name' />
            <span class='book-name'>$product_name</span>
            </a>
             <a href='product.php?id=$id' class='buy-btn'>RM<span class='price'>$price</span></a>
            </div>
            </li>

            ";
        }//While loop was not closed

    } else {
        $search_output = "<hr />0 results for <strong>$searchquery</strong><hr />";
    }
}
?>

你还需要绑定所有5个参数,改变以下行。

$stmt->bind_param('s', '%$searchquery%');

修改

$stmt->bind_result($product_name, $price);
如果第三列是总分,则

应如下所示。使用*select

时,无法知道列名称
$stmt->bind_result($product_name, $price, $totalpoints);

printf("%s %s\n", $product_name, $price, $totalpoints);

可以

printf("%s %s %s\n", $product_name, $price, $totalpoints);

或者只是

echo "$product_name $price $totalpoints\n";

在执行语句后获得总使用量。

$count = $stmt->num_rows;

编辑2 检查这是否也有效。

$search_output = "";

if (isset($_POST['searchquery']) && $_POST['searchquery'] != "") {
    $searchquery = preg_replace('/[^a-zA-Z0-9_ %\[\]\/\.\(\)%&-]/s', '', $_POST['searchquery']);
    if ($_POST['filter1'] == "Products") {
        require_once ("storescripts/connect_to_mysqli.php");
        $stmt = $myConnection->prepare('SELECT id, product_name, price FROM products WHERE product_name LIKE ? OR details LIKE ? OR category LIKE ? OR subcategory LIKE ? OR price LIKE ?');
        $param = "%$searchquery%";
        $stmt->bind_param('sssss', $param, $param, $param, $param, $param);
        $stmt->execute();
        /* store result */
        $stmt->store_result();
        /* get the row count */
        $count = $stmt->num_rows;
        if ($count >= 1) {
            $search_output = "<hr />$count results for <strong>$searchquery</strong><hr />";
            $stmt->bind_result($id, $product_name, $price);

            while ($stmt->fetch()) {
                printf("%s %s %s\n", $id, $product_name, $price);
                $search_output .= "
                <li><div class='product'>
                <a href='product.php?id=$id' class='info'>
                <span class='holder'>
                <img src='inventory_images/$id.jpg' alt='$product_name' />
                <span class='book-name'>$product_name</span>
                </a>
                 <a href='product.php?id=$id' class='buy-btn'>RM<span class='price'>$price</span></a>
                </div>
                </li>

                ";
            }
        } else {
            $search_output = "<hr />0 results for <strong>$searchquery</strong><hr />";
        }

    } else {
        $search_output = "<hr />0 results for <strong>$searchquery</strong><hr />";
    }
}