以下脚本的作用(或应该做什么):
- 连接到数据库
- 包括创建 5 位数代码的功能
- 用户输入他们的电子邮件地址
- 检查电子邮件是否有效
- 将电子邮件插入“电子邮件”列
- 检查电子邮件是否已存在,如果存在,请让用户知道并中断脚本
- 运行创建 5 位数代码的函数
- 检查“unique_code”列是否已存在,如果存在,则从 5 位代码创建函数循环
- 如果所有内容都有效,则隐藏表单并显示(来自单独 JS 的 ajax)谢谢 div
- 向用户显示唯一代码
一切都会运行,但是 unique_code 不会插入到数据库中,并且在“谢谢!”时不会显示。
我做错了什么,需要修改什么?
谢谢!
代码
<?php
require "includes/connect.php";
function generateCode($length = 5) {
$characters = 'bcdfghjkmnpqrstvwxyz';
$string = '';
for ($i = 0; $i < $length; $i++) {
$string .= $characters[rand(0, strlen($characters) - 1)];
}
return $string;
}
$msg = '';
if($_POST['email']){
// Requested with AJAX:
$ajax = ($_SERVER['HTTP_X_REQUESTED_WITH'] == 'XMLHttpRequest');
try{
//validate email
if(!filter_input(INPUT_POST,'email',FILTER_VALIDATE_EMAIL)){
throw new Exception('Invalid Email!');
}
//insert email
$mysqli->query("INSERT INTO coming_soon_emails
SET email='".$mysqli->real_escape_string($_POST['email'])."'");
//if already exists in email column
if($mysqli->affected_rows != 1){
throw new Exception('You are already on the notification list.');
}
if($ajax){
die('{"status":1}');
}
//start creating unique 5 digit code
$unique_code = "";
$inserted = false;
// Keep looping until we've inserted a record
while(!$inserted) {
// Generate a code
$unique_code = generateCode();
// Check if it exists
if ($result = $mysqli->query("SELECT unique_code FROM coming_soon_emails WHERE unique_code = '$unique_code'")) {
// Check no record exists
if ($result->num_rows == 0) {
// Create new record
$mysqli->query("INSERT INTO coming_soon_emails (email,unique_code) VALUES ('" . $mysqli->real_escape_string($_POST['email']) . "','$unique_code')");
// Set inserted to true to ext loop
$inserted = true;
// Close the result object
$result->close();
}
} else {
// Quit if we can't check the database
die('Something went wrong with select');
}
}
}
catch (Exception $e){
if($ajax){
die(json_encode(array('error'=>$e->getMessage())));
}
$msg = $e->getMessage();
}
}
?>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>example</title>
<link rel="stylesheet" type="text/css" href="css/styles.css" />
</head>
<body>
<div id="container">
<form id="form" method="post" action="">
<input type="text" id="email" name="email" value="<?php echo $msg?>" />
<input type="submit" value="Submit" id="submitButton" />
</form>
<div id="thankyou">
Thank you! <?php echo $unique_code;?></p>
</div>
</div>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.3/jquery.min.js"></script>
<script src="js/script.js"></script>
</body>
</html>
最佳答案
您似乎在类定义之外使用了 private
关键字,这是不允许的。
关于PHP/MySQL 不会按应有的方式插入和回显?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5314635/