我使用PHP创建了一个订阅按钮。每当我点击订阅按钮,而不是去数据库,它会被卡在filter_var()PHP代码上,这些代码回显了正确的电子邮件。经过深思熟虑,我无法弄清楚问题。 这是我的PHP代码
<?php
include 'conn.php';
$email=mysqli_real_escape_string($conn, $_POST['email']);
if (isset($_POST['submit'])) {
$sql= "SELECT * FROM subscribe WHERE email='$email'";
$result=mysqli_query($conn, $sql);
$row=mysqli_num_rows($result);
if ($email=mysqli_fetch_assoc($result)) {
echo "<span style='color:red'>*you are already subscribed</span>";
}else{
if (filter_var($email, FILTER_VALIDATE_EMAIL)) {
echo "<span>Put correct email<span>";
}else{
$enter= "INSERT INTO `subscribe` (`id`, `email`) VALUES (NULL, '$email');";
msqli_query($conn, $enter);
echo "<span style='color:green;'>Thank you for subscribing";
}
}
} else{
echo "something went wrong";
}
?>
请参阅此代码
if (filter_var($email, FILTER_VALIDATE_EMAIL)) {
echo "<span>Put correct email<span>";
当上半部分正常工作时,它会卡在这一部分,即当我输入相同的电子邮件时它会运行回声功能。
我也在使用jquery在同一页面上运行该功能
<script>
$(document).ready(function () {
$('#subscribe-form').submit(function(event) {
event.preventDefault();
var email=$("input[name='email']").val();
var submit=$("#submit").val();
$('.sub').load('subscription.inc.php', {
email:email,
submit:submit
})
});
});
</script>
答案 0 :(得分:1)
请更改条件:
if (filter_var($email, FILTER_VALIDATE_EMAIL)) {
echo "<span>Put correct email<span>";
为:
if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
echo "<span>Put correct email<span>";
因为filter_var()
返回过滤后的文字。并在此返回一些文本,以便条件成真。
答案 1 :(得分:0)
如果您有自动增量,则需要从查询中删除Id。因为数据库管理自己。 而你在这里打字错误。
msqli_query($conn, $enter);
应该是
mysqli_query($conn, $enter);
并改变
if ($email=mysqli_fetch_assoc($result)) {
使用
if ($row>0) {
完整代码:subscription.inc.php
<?php
include 'conn.php';
if (isset($_POST['submit'])) {
$email=mysqli_real_escape_string($conn, $_POST['email']);
$sql= "SELECT * FROM subscribe WHERE email='$email'";
$result=mysqli_query($conn, $sql);
$row=mysqli_num_rows($result);
if ($row>0) {
echo "<span style='color:red'>*you are already subscribed</span>";
}
else
{
if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
echo "<span>Put correct email<span>";
}
else
{
$enter= "INSERT INTO `subscribe` (`email`) VALUES ('$email')";
mysqli_query($conn, $enter);
echo "<span style='color:green;'>Thank you for subscribing";
}
}
}
?>
和html表单:
<!DOCTYPE html>
<html>
<head>
<title></title>
</head>
<body>
<form method="post" action="subscription.inc.php" id="subscribe-form">
<input type='text' placeholder="enter your email" name="email" id="#email">
<br/>
<button class="btn" role="button" type="submit" name="submit" id="submit"> subscribe </button>
<p class="sub"></p>
</form>
</body>
</html>