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

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
iCeR
Forum Newbie
Posts: 5
Joined: Tue Feb 08, 2011 9:29 am

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

Post by iCeR »

What the following script does (or should do):

- Connects to DB
- Includes a function for creating a 5 digit code
- 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 funtion for creating a 5 digit code
- Checks the 'unique_code' column if it already exists, if so, loop from 5 digit code creation function
- If all is valid, hide the form and display the (ajax from a seperate JS) thank you 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! <?php echo $unique_code;?>".

What am I doing wrong and what needs to be modified?

Thank you!

Code

Code: Select all

       <?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>
User avatar
akuji36
Forum Contributor
Posts: 190
Joined: Tue Oct 14, 2008 9:53 am
Location: Hartford, Connecticut

Re: PHP/MySQL won't INSERT and echo as it should?

Post by akuji36 »

Just took a quick glance at your code.

I noticed that after the comment 'insert email' the actual mysqli insert statement

looks like an insert statement combined with an update statement (see set).

Regarding your unique code variable... does it refer to column in your database

or should it generate a unique code (a number ) like the php rand function?
Post Reply