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

问题描述:

也有恶意插入

Also malicious inserts

我已经看到了这个问题,但是没有一个答案对我有用(或者我太愚蠢而无法使它们起作用).我想我需要个性化的帮助.每次刷新php页面时,它都会插入空白数据.如何防止插入空白和/或恶意数据.

I've seen this question asked but none of the responses worked for me (or rather I was too stupid to make them work). I think I need personalized help. Every time I refresh my php page it inserts blank data. How do I prevent blank and/or malicious data from being inserted.

这是我的代码:

 <?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> 

用一些防御性的逻辑将其包装:

Wrap it with some defensive logic:

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

    // Your code here
}