以下脚本执行(或应该执行)的操作:
一切都在运行,但是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>
答案 0 :(得分:2)
您似乎在类定义之外使用private
关键字,这是不允许的。
答案 1 :(得分:0)
你在coming_soon_emails表中的'email'上有一个主键吗?由于您已经为给定的电子邮件地址插入了一个条目,这将使您无法插入具有唯一值的第二个条目。
确定唯一密钥后,为什么不进行UPDATE而不是INSERT?