简体   繁体   English

PHP / MySQL不会INSERT和回应它应该吗?

[英]PHP/MySQL won't INSERT and echo as it should?

What the following script does (or should do): 以下脚本的作用(或应该如何):

  • Connects to DB 连接到DB
  • Includes a function for creating a 5 digit code 包括用于创建5位数代码的功能
  • User enters their email address 用户输入其电子邮件地址
  • Checks if it's a valid email 检查它是否是有效的电子邮件
  • Inserts the email into the 'email' column 将电子邮件插入“电子邮件”列
  • Checks if email already exists, if so, let the user know and break script 检查电子邮件是否已存在,如果是,请让用户知道并破坏脚本
  • Runs the function for creating a 5 digit code 运行用于创建5位数代码的功能
  • Checks the 'unique_code' column if it already exists, if so, loop from 5 digit code creation function 检查'unique_code'列是否已存在,如果已存在,则从5位数代码创建函数循环
  • If all is valid, hide the form and display the (ajax from a separate JS) thank you div 如果一切都有效,隐藏表格并显示(来自单独的JS的ajax)谢谢div
  • Display the unique code to the user 向用户显示唯一代码

Everything runs, however the unique_code is not inserted into the DB and is not displayed when it does "Thank you! ". 一切都在运行,但是unique_code没有插入到DB中,并且在“谢谢!”时不会显示。

What am I doing wrong and what needs to be modified? 我做错了什么,需要修改什么?

Thank you! 谢谢!

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关键字,这是不允许的。

Do you have a primary key on 'email' in the coming_soon_emails table? 你在coming_soon_emails表中的'email'上有一个主键吗? Since you've already inserted one entry for the given email address, that would keep you from inserting a second entry with the unique value. 由于您已经为给定的电子邮件地址插入了一个条目,因此可以防止您插入具有唯一值的第二个条目。

Why not do an UPDATE instead of an INSERT once you have determined the unique key? 一旦确定了唯一密钥,为什么不进行UPDATE而不是INSERT?

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM