开发者

how to add some php to this tutorial, mysql query included?

Tutorial is here: http://tutorialzine.com/2010/10/ajaxed-coming-soon-page/

Where it does this:

15          $mysqli->query("INSERT INTO coming_soon_emails
16                          SET email='".$mysqli->real_escape_string($_POST['email'])."'");
17   
18          if($mysqli->affected_rows != 1){
19              throw new Exception('This email already exists in the database.');
20          }

Once it checks the email is not a duplicate, I would like it to add a unique (no two email records should have the same) Alphanumeric code like this: AQ4ILB9

Then when the user gets the "Thank you!" message in the textbox, I want it to also display the unique code as above.

I have to setup a new column in the DB for the addition of a code, correct? What properties must it have when adding to do the above code insertion? Possibly automatically creating the unique code for each record so the DB does the random code insertion work rather than a loop check in php?

How can I display the code to the user once the "Thank you!" message is displayed.

Any help editing the tutorial would be much appreciated!

Thanks!

table.sql file

--
-- Table structure for table `coming_soon_emails`
--

CREATE TABLE `coming_soon_emails` (
  `email` varchar(64) collate utf8_unicode_ci NOT NULL,
  `ts` timestamp NOT NULL default CURRENT_TIMESTAMP,
  PRIMARY KEY  (`email`)
) E

ADDITIONAL EDIT

hidden div on coming-soon.php

<div id="code">
Thank you! Your code is: <p style="margin-top:20px;"><?php echo $ref_code;?></p>
</div>

with that I also had to replace

$msg = "Thank you! Subscription Code: " . $email_code;

with

$ref_code = "example.com/" . $email_code;

Now if you check out the script.js file, mine has been modified to:

$(document).ready(function(){

    // Binding event listeners for the form on document ready

    $('#email').defaultText('Your Email Address');

    // 'working' prevents multiple submissions
    var working = false;

    $('#form').submit(function(){

        if(working){
            return false;
        }
        working = true;

        $.post("./index.php",{email:$('#email').val()},function(r){
            if(r.error){
                $('#email').val(r.error);
            }
            else { $("#form").hide(); $("#code").fadeIn('slow');}

            working = false;
        },'json');

        return false;
    });
});

// A custom jQuery method for placeholder text:

$.fn.defaultText = 开发者_运维技巧function(value){

    var element = this.eq(0);
    element.data('defaultText',value);

    element.focus(function(){
        if(element.val() == value){
            element.val('').removeClass('defaultText');
        }
    }).blur(function(){
        if(element.val() == '' || element.val() == value){
            element.addClass('defaultText').val(value);
        }
    });

    return element.blur();
}

However, the else { $("#form").hide(); $("#invite").fadeIn('slow');} is no longer working! Thoughts?


For your second question, to fix the ajax:

        if(r.error){
            $('#email').val(r.error);
        } else {
           $('#email').val(r.msg); 
               $("#form").hide(); $("#code").fadeIn('slow');
        }

and in the php script fix:

    $msg = "Thank you! Subscription Code: " . $email_code;

    if($ajax){
        echo json_encode(array('msg' => $msg)); // add this
        //throw new Exception($msg);  // delete this
    }

You will need to modify to suit your variations...

New files:

https://colorchallenge.com/comingsoon/cs.txt (php)

https://colorchallenge.com/comingsoon/script.txt (javascript)


http://www.colorchallenge.com/comingsoon/coming-soon.php

http://www.colorchallenge.com/comingsoon/coming-soon.txt

and the SQL: http://www.colorchallenge.com/comingsoon/table.sql

New alternate answer with truly random code:

Updated SQL Table:

CREATE TABLE IF NOT EXISTS `coming_soon_emails` (   
  `email_id` int(11) NOT NULL auto_increment,   
  `email` varchar(64) collate utf8_unicode_ci NOT NULL,   
  `code` char(7) collate utf8_unicode_ci DEFAULT NULL,
  `ts` timestamp NOT NULL default CURRENT_TIMESTAMP,   
  PRIMARY KEY  (`email_id`),   
  UNIQUE KEY `email` (`email`),
  UNIQUE KEY `code` (`code`)
) ENGINE=MyISAM DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; 

in comming-soon.php:

Add after: "includes/connect.php";

function gen_code($codeLen = 7) {
    $code = '';
    for ($i=0; $i<$codeLen; $i++) { 
        $d=rand(1,30)%2; 
        $code .= $d ? chr(rand(65,90)) : chr(rand(48,57)); 
    } 
    return $code;
}

function add_code($email_id) {
    $code = gen_code(7);
    $mysqli->query("UPDATE coming_soon_emails SET code='" . $code ."' WHERE email_id='" . $email_id . "'");
    if($mysqli->affected_rows != 1) {
      add_code($email_id);
    } else return $code;
}

Then modify:

if($mysqli->affected_rows != 1){     
    throw new Exception('This email already exists in the database.'); 
} 

To be:

if($mysqli->affected_rows != 1){     
    throw new Exception('This email already exists in the database.'); 
} else {
  $email_code = add_code($mysqli->insert_id);
}

Finally, update the message again to include the code... Change:

$msg = "Thank you!"; 

To be:

$msg = "Thank you! Subscription Code: " . $email_code;

Also (without editing the javascript) to make sure it provides the response you may want to change:

    if($ajax){
        die('{"status":1}');
    }

    $msg = "Thank you! Subscription Code: " . $email_code;

to:

    $msg = "Thank you! Subscription Code: " . $email_code;
    if($ajax){
      throw new Exception($msg);
    }

Essentially the last change just makes it always throw an exception.. which then makes sure the message is displayed if its an ajax request

---


Full Final Copy of coming-soon.php

<?php

require "includes/connect.php";

function gen_code($codeLen = 7) {     
$code = '';     
for ($i=0; $i<$codeLen; $i++) {         
 $d=rand(1,30)%2;       
 $code .= $d ? chr(rand(65,90)) : chr(rand(48,57));      }  
 return $code; 
 }  


 function add_code($email_id) {
 global $mysqli;
 $code = gen_code(7); 
 $mysqli->query("UPDATE coming_soon_emails SET code='" . $code ."' WHERE email_id='" . $email_id . "'");  
 if($mysqli->affected_rows != 1) {   
 add_code($email_id);  
 } else return $code; } 

$msg = '';

if($_POST['email']){

    // Requested with AJAX:
    $ajax = ($_SERVER['HTTP_X_REQUESTED_WITH']  == 'XMLHttpRequest');

    try{
        if(!filter_input(INPUT_POST,'email',FILTER_VALIDATE_EMAIL)){
            throw new Exception('Invalid Email!');
        }

        $mysqli->query("INSERT INTO coming_soon_emails
                        SET email='".$mysqli->real_escape_string($_POST['email'])."'");

        if($mysqli->affected_rows != 1){
            throw new Exception('This email already exists in the database.');
        } else {   
          $email_code = add_code($mysqli->insert_id); 
        } 


    $msg = "Thank you! Subscription Code: " . $email_code;

    if($ajax){
        throw new Exception($msg);
    }



    }
    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>AJAX-ed Coming Soon Page with jQuery and PHP | Tutorialzine Demo</title>

<link rel="stylesheet" type="text/css" href="css/styles.css" />
<link rel="stylesheet" type="text/css" href="css/nivo-slider.css" />

</head>

<body>

<div id="page">

    <h1>Coming Soon</h1>

    <div id="slideshowContainer">
        <div id="slideshow">
            <img src="img/slides/slide1.jpg" width="454" height="169" alt="Coming Soon: Our Awesome Web App">
            <img src="img/slides/slide2.jpg" width="454" height="169" alt="Extensive Functionality">
            <img src="img/slides/slide3.jpg" width="454" height="169" alt="Complete with an iPhone App">
        </div>
    </div>

    <h2>Subscribe</h2>

    <form method="post" action="">
        <input type="text" id="email" name="email" value="<?php echo $msg?>" />
        <input type="submit" value="Submit" id="submitButton" />
    </form>

</div>

<!-- Feel free to remove this footer -->

<div id="footer">
    <div class="tri"></div>
    <h1>AJAX-ed Coming Soon Page</h1>
    <a class="tzine" href="http://tutorialzine.com/2010/10/ajaxed-coming-soon-page/">Read &amp; Download on</a>
</div>

<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.3/jquery.min.js"></script>
<script src="js/jquery.nivo.slider.pack.js"></script>
<script src="js/script.js"></script>

</body>
</html>


You will first have to create a new column and set it to be a Unique key. This means that no two rows can have the same value for that column. If you try inserting a value into an Unique row that another row already has, mysql will not. With this being said, you have two options:

Set that row to unique, make it an index, and set it to auto increment. This will make it so that for every row created, a number will be inserted that is 1 more than the previous one (such as 1,2,3,4.. each row basically gets a unique number).

If you want something more than just a unique number, you can use the following code. Just make sure to create a row in the database table called "code" and set it to be a unique key.

$email = mysql_real_escape_string($_POST['email']); // Secure input to prevent database injection attacks

// Insert a row into mysql with the e-mail
$mysqli->query("INSERT INTO coming_soon_emails
              SET email='".$mysqli->real_escape_string($email)."'");

// Check if row was created successfully (only successful if e-mail is unique)
if($mysqli->affected_rows != 1){ // If no row was created, try again.
    throw new Exception('This email already exists in the database.');
}

function genkey($length = 7) // Function to generate a random string
{

    // Set possible characters (characters that can be in the generated string)
    $possible = "0123456789abcdefghijklmnopqrstuvwxyz"; 

    // start with a blank string
    $string = "";

    // set up a counter
    $i = 0; 

    // add random characters to $string until $length is reached
    while ($i < $length) 
    { 

        // pick a random character from the possible ones
        $string .= substr($possible, mt_rand(0, strlen($possible)-1), 1);
        $i++;

    }

    // done!
    return $string;

}

function make_code($email) // Function to add unique key to database
{

    // Generate a random 7 character string for the unique key. Change the 7 to however long you want the unique code to be.
    $randString = genkey(7);

    // Try insterting a unique key
    $mysqli->query("UPDATE coming_soon_emails
              SET code='" . $string . "' WHERE email='".$email."'");

    // Ensure that row was updated with a unique code. If not, try again with a different code.
    if($mysqli->affected_rows != 1){ 
        make_code($email); // Row was not updated since code is not unique. Try again.
    }

}

The code is explained in the comments. It basically creates the database row like you were doing before, then tries setting a unique code value for that row. If mysql returns that no rows were updated by the query trying to set a unique code, that means that code was not unique. It will keep trying until a unique code is made.

If you are having trouble setting a column to be unique, auto-increment, and so forth.. take a look into phpMyAdmin. It is excellent for people starting out with this stuff.


UPDATE: Better coderandomization: Plug this into users* code and give it a whirl

function genkey($codeLen = 7) {
    $code = '';
    for ($i=0; $i<$codeLen; $i++) { 
        $d=rand(1,30)%2; 
        $code .= $d ? chr(rand(65,90)) : chr(rand(48,57)); 
    } 
    return $code;
}

Origional response:

If you simply want to work with a simple unsecure code instead of an email address, you could use hex plus a base for a 'code' value...

First, update your table so it has an auto increment primary key, and email as a secondary unique key..

CREATE TABLE IF NOT EXISTS `coming_soon_emails` (
  `email_id` int(11) NOT NULL auto_increment,
  `email` varchar(64) collate utf8_unicode_ci NOT NULL,
  `ts` timestamp NOT NULL default CURRENT_TIMESTAMP,
  PRIMARY KEY  (`email_id`),
  UNIQUE KEY `email` (`email`)
) ENGINE=MyISAM DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;

Then, in the example code (comming-soon.php around line 17) modify:

if($mysqli->affected_rows != 1){
    throw new Exception('This email already exists in the database.');
}

to be:

if($mysqli->affected_rows != 1){
   throw new Exception('This email already exists in the database.');
} else {
   $email_id = $mysqli->insert_id;
   $email_code = dechex($email_id + 1000000);  // just makes the code longer
}

Finally, change comming-soon.php (around line 28) from:

    $msg = "Thank you!";

To be:

    $msg = "Thank you! Subscription ID: " . $email_code;

Then if you want to work with unsubscribe you simply unhex the number and subtract whateverwas added to it (10000000 in my example)...

It just depends on how 'secure' you want the code... The other examples given are great for security.. But if your simply wanting a code instead of email, the hex route is the simplest...


<?php

require "includes/connect.php";

function genkey($codeLen = 7) {
    $code = '';
    for ($i=0; $i<$codeLen; $i++) { 
        $d=rand(1,30)%2; 
        $code .= $d ? chr(rand(65,90)) : chr(rand(48,57)); 
    } 
    return $code;
}


function make_code($email) // Function to add unique key to database
{

    // Generate a random 7 character string for the unique key. Change the 7 to however long you want the unique code to be.
    $randString = genkey(7);

    // Try insterting a unique key
    $mysqli->query("UPDATE coming_soon_emails
              SET code='" . $string . "' WHERE email='".$email."'");

    // Ensure that the row was updated with a unique code. If not, try again.
$c = $mysqli->fetch_array(query("SELECT count(*) FROM coming_soon_email WHERE code = '$randString'"));

if($c['count(*)'] > 1) // More than one row already has this code. Try again.
{

    make_code($email);  

}


}

$msg = '';

if($_POST['email']){

    // Requested with AJAX:
    $ajax = ($_SERVER['HTTP_X_REQUESTED_WITH']  == 'XMLHttpRequest');

    try{
        if(!filter_input(INPUT_POST,'email',FILTER_VALIDATE_EMAIL)){
            throw new Exception('Invalid Email!');
        }

        $email = mysql_real_escape_string($_POST['email']); // Secure input to prevent database injection attacks

// Insert a row into mysql with the e-mail
$mysqli->query("INSERT INTO coming_soon_emails
              SET email='".$mysqli->real_escape_string($email)."'");

// Check if row was created successfully (only successful if e-mail is unique)
if($mysqli->affected_rows != 1){ // If no row was created, try again.
    throw new Exception('This email already exists in the database.');
}


        if($ajax){
            die('{"status":1}');
        }

        $msg = "Thank you!";
    }
    catch (Exception $e){

        if($ajax){
            die(json_encode(array('error'=>$e->getMessage())));
        }

        $msg = $e->getMessage();        
    }
}
?>
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜