为什么要将空白数据插入数据库

时间:2015-11-18 17:44:30

标签: php mysqli

我不理解将空白数据插入数据库的想法,我尝试了很多来自堆栈溢出和其他许多站点的示例。论坛但从未找到我的解决方案,请帮助我。

这是我的代码:

<form action="index.php" method="post">
    <input type="email" class="incsub-mailchimp-field" name="email" placeholder="Enter your email address" required=""/>
    <input type="submit" name="subscribe" class="incsub-mailchimp-submit" value="Subscribe"/>
</form>

<?php
 $email="";  

if (isset($_POST['subscribe'])) 
{
  $email = $_POST['email'];
}

 // attempt insert query execution
 mysqli_query($mysqli, ("INSERT INTO email_list (email,created)
 VALUES ('$email',now())"));
?>

3 个答案:

答案 0 :(得分:0)

试试这个:

<?php
 $email="";  

if (isset($_POST['subscribe'])) 
{
  $email = $_POST['email'];
 // attempt insert query execution
 mysqli_query($mysqli, ("INSERT INTO email_list (email,created)
 VALUES ('$email',now())"));
}
?>

仅在字段POST时插入数据库。

答案 1 :(得分:0)

你检查过isset(($ _ POST [&#39; subscribe&#39;])但是在if条件之外插入查询

<html>
<form action="index.php" method="post">
<input type="email" class="incsub-mailchimp-field" name="email" placeholder="Enter your email address" required=""/>
<input type="submit" name="subscribe" class="incsub-mailchimp-submit" value="Subscribe"/>
</form>
</html>
<?php
 $email="";  
if (isset($_POST['subscribe'])) 
{
$email = $_POST['email'];
mysqli_query($mysqli,"INSERT INTO email_list (email,created) VALUES ('$email',now())");
}
?>

答案 2 :(得分:0)

您也可以通过此方法执行此操作,我认为它更有意义

<form action="<?php echo htmlspecialchars($_SERVER['PHP_SELF']);?>" method="post">
    <input type="email" class="incsub-mailchimp-field" name="email" placeholder="Enter your email address" required=""/>
    <input type="submit" name="subscribe" class="incsub-mailchimp-submit" value="Subscribe"/>
</form>

<?php
 $email="";  

if ($_SERVER['REQUEST_METHOD'] == "POST") 
{
  $email = $_POST['email'];   

 // attempt insert query execution
 mysqli_query($mysqli, ("INSERT INTO email_list (email,created)
 VALUES ('$email',now())"));
}
?>

$_SERVER["PHP_SELF"]是一个超级全局变量,它返回当前正在执行的脚本的文件名。使用htmlspecialchars();可以防止跨站点脚本攻击