如果用户没有输入电子邮件而没有向表中添加列,我正在尝试显示错误消息。
php代码发送电子邮件&随机生成的代码到数据库,然后显示一条消息,但如果他们没有输入电子邮件,我试图收到一条消息要求发送电子邮件,而不是创建一个列,直到完成。
我之前已经通过其他数据输入实现了这一点,但我还是PHP新手,我已经检查了答案,但不能找到我知道的简单修复。
非常感谢任何帮助或评论,谢谢(Y)
PHP:
<?php
if(!empty($_POST['email'])) {
?>
<p>Enter an email</p>
<?php
}
if(isset($_POST['send'])){
$email = mysqli_real_escape_string($conn,$_POST['email']);
$length = 10;
$inviteCode = "";
$characters = "0123456789abcdefghijklmnopqrstuvwxyz";
for ($p = 0; $p < $length; $p++) {
$inviteCode .= $characters[mt_rand(10, strlen($characters))];
}
$query = mysqli_query($conn, "INSERT INTO `referrals` (`email`, `inviteCode`)
VALUES ('$email', '$inviteCode') ");
if($query){
?>
<p> "Thank you"</p>
<?php
}
else{
?>
<p>Sorry there must have been a problem</p>
<?php
die('Error querying database. ' . mysqli_error($conn));
}
} // end brace for if(isset($_POST['Login']))
// end brace for if(isset($_POST['Login']))
?>
我之前通过将以下内容放在首位来实现这一目标;
if (empty($_POST) === false) {
$required_fields = array('email');
foreach($_POST as $key=>$value) {
if (empty($value) && in_array($key, $required_fields) === true) {
$errors[] = 'Please Enter All Information';
break 1;
}
}
}
提交和电子邮件输入标记的html代码如下:
<input type="text" placeholder="Email" name="email" />
<input type="submit" value="send" name="send" />
答案 0 :(得分:2)
将if(!empty($_POST['email']))
添加到逻辑顶部,而不是isset($_POST['send'])
,除非您在逻辑中稍后使用post send值执行其他操作。如果有一个空字符串,则isset将为true。
要了解原因,请参阅:
isset() and empty() - what to use
修改强>
<?php
if(!empty($_POST)){
if(!empty($_POST['email'])){
$email = mysqli_real_escape_string($conn,$_POST['email']);
$length = 10;
$inviteCode = "";
$characters = "0123456789abcdefghijklmnopqrstuvwxyz";
for ($p = 0; $p < $length; $p++) {
$inviteCode .= $characters[mt_rand(10, strlen($characters))];
}
$query = mysqli_query($conn, "INSERT INTO `referrals` (`email`, `inviteCode`) VALUES ('$email', '$inviteCode') ");
//you might want to consider checking more here such as $query == true as it can return other statuses that you may not want
if($query){
?>
<p> "Thank you"</p>
<?php
}
else{
?>
<p>Sorry there must have been a problem</p>
<?php
die('Error querying database. ' . mysqli_error($conn));
}
}
else {
?>
<p>Enter an email</p>
<?php
}
}
?>
答案 1 :(得分:1)
试试这个:
<?php
// check if email is empty, if it is display this message
if(empty($_POST['email'])) {
?>
<p>Enter an email</p>
<?php
}
// else: the user entered something
else {
$email = mysqli_real_escape_string($conn,$_POST['email']);
$length = 10;
$inviteCode = "";
$characters = "0123456789abcdefghijklmnopqrstuvwxyz";
for ($p = 0; $p < $length; $p++) {
$inviteCode .= $characters[mt_rand(10, strlen($characters))];
}
$query = mysqli_query($conn, "INSERT INTO `referrals` (`email`, `inviteCode`)
VALUES ('$email', '$inviteCode') ");
if($query){
?>
<p> "Thank you"</p>
<?php
}
else {
?>
<p>Sorry there must have been a problem</p>
<?php
die('Error querying database. ' . mysqli_error($conn));
} // end else
} // end else
?>