如何防止空白数据插入MySQL表


How Do I Prevent Blank Data from being Inserted into a MySQL Table?

还有恶意插入

我见过有人问我这个问题,但没有一个答案对我有效(或者说我太愚蠢了,无法让它们发挥作用)。我想我需要个性化的帮助。每次刷新php页面时,它都会插入空白数据。如何防止插入空白和/或恶意数据。

这是我的代码:

 <?php
    $con = mysql_connect("localhost","user","pass") or die ("Couldn't connect!");
    if (!$con)
    {
        die('Could not connect: ' . mysql_error());
    }
    mysql_select_db("streams") or die ("Couldn't find db");
    $sql="INSERT INTO streams (streamname)
    VALUES ('$_POST[streamname]')";
    if (!mysql_query($sql,$con))
    {
        die('Error: ' . mysql_error());
    }
    echo "1 record added";

    mysql_close($con)
?>
<form action="submit.php" method="POST">
    Stream Name: <input type="text" name="streamname" id="streamname" /><br />
    <input type="submit" name="submit" value="Stream" />
</form> 

用一些防御逻辑包装它:

if(!empty($_POST['streamname'])) {
    // Your code here
}

尝试检查是否设置了POST参数:

 <?php
if($_POST) {
    $con = mysql_connect("localhost","user","pass") or die ("Couldn't connect!");
    if (!$con)
    {
        die('Could not connect: ' . mysql_error());
    }
    mysql_select_db("streams") or die ("Couldn't find db");
    $sql="INSERT INTO streams (streamname)
    VALUES ('$_POST[streamname]')";
    if (!mysql_query($sql,$con))
    {
        die('Error: ' . mysql_error());
    }
    echo "1 record added";

    mysql_close($con);
}
?>
<form action="submit.php" method="POST">
    Stream Name: <input type="text" name="streamname" id="streamname" /><br />
    <input type="submit" name="submit" value="Stream" />
</form> 

您应该对输入进行转义。

$sql='INSERT INTO streams (streamname)
VALUES ("'.mysql_real_escape_string($_POST[streamname]).'")';