我有一个HTML表单用于更新我的数据库中的内容,如果我在我的表单的输入字段中输入一个单引号,sql更新失败


I have a HTML form used to update content in my DB, if I type in a single quote in the input field of my form, the sql update fails

我有一个非常简单的表单,当我输入到表单输入字段,数据被传递到一个php脚本,它将数据添加到我的数据库。但是,如果我输入带有撇号或单引号的内容,则会中断查询,并且数据不会添加到我的数据库中。

形式代码

<form method="POST" action="#">
        <table>
            <tr>
                <td><label>Title: </label><br><input type="text" name="title1" placeholder="<?php echo htmlspecialchars($deal1title); ?>"></td>
            </tr>
            <tr>
                <td>
                    <label>Description: </label><br><textarea style="height: 200px;" name="desc1" placeholder="<?php echo htmlspecialchars($deal1desc); ?>"></textarea>
                </td>
            </tr>
            <tr>
                <td><label>Price: </label><br><input type="text" name="price1" placeholder="<?php echo htmlspecialchars($deal1price); ?>"></td>
            </tr>
            <tr>
                <td><label>Include: </label><br><input type="text" name="include1" placeholder="<?php echo htmlspecialchars($deal1inc); ?>"></td>
            </tr>
            <tr>
                <td><label>Not Include: </label><br><input type="text" name="notinc1" placeholder="<?php echo htmlspecialchars($deal1noinc); ?>"></td>
            </tr>
            <tr>
                <td><input type="submit" name="submit1" value="Save"></td>
            </tr>
        </table>
    </form>
PHP代码

if(isset($_POST['submit1'])){
    $getTitle1=$_POST["title1"];
    $getDesc1=$_POST["desc1"];
    $getPrice1=$_POST["price1"];
    $getInc1=$_POST["include1"];
    $getNoInc=$_POST["notinc1"];
        //Set Title
        if(!empty($getTitle1)){
        mysqli_query($connect, "UPDATE specials SET title='$getTitle1' WHERE id=1");
        }
        //Set Description
        if(!empty($getDesc1)){
            mysqli_query($connect, "UPDATE specials SET description='$getDesc1' WHERE id=1");    
        }
        //Set Price
        if(!empty($getPrice1)){
        mysqli_query($connect, "UPDATE specials SET price='$getPrice1' WHERE id=1");
        }
        //Set Include
        if(!empty($getInc1)){
            mysqli_query($connect, "UPDATE specials SET include='$getInc1' WHERE id=1");
        }
        //Set noinclude
        if(!empty($getNoInc)){
            mysqli_query($connect, "UPDATE specials set notinclude='$getNoInc' WHERE id=1");
        }

    }

这就是为什么您必须小心转义放入查询中的数据,或者最好使用准备好的语句。您的代码目前容易受到sql注入攻击。

快速而肮脏的方法是对进入查询的所有变量使用mysqli_real_escape_string()来转义任何特殊字符。例如:
mysqli_query($connect, "UPDATE specials SET description='".mysqli_real_escape_string($connect, $getDesc1)."' WHERE id=1"); 

一个更好的解决方案是使用PHP的PDO驱动程序来代替准备语句。例如:

$stmt = $db->prepare("UPDATE specials SET description=? WHERE id=1");
$stmt->execute(array($getDesc1));

PDO为您处理所有数据卫生,从而解决您的问题,同时防止SQL注入攻击。

相关文章: