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

时间:2012-01-10 00:43:00

标签: php mysql database

也是恶意插入

我已经看到这个问题,但没有一个回复对我有用(或者说我太愚蠢了,不能让它们起作用)。我想我需要个性化的帮助。每次刷新我的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> 

3 个答案:

答案 0 :(得分:5)

用一些防御逻辑包裹它:

if(!empty($_POST['streamname'])) {

    // Your code here
}

答案 1 :(得分:2)

尝试检查是否设置了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> 

答案 2 :(得分:0)

你应该逃避输入。

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