简体   繁体   中英

PDO Insert not working (PHP/MySQL)

After days of trial and error, I finally replaced my standard mysql code with PDO. Everything seems to be working just fine except for the last part where the app needs to INSERT user (name, email and time of signup) into database. After clicking submit, page just turns blank.

I don't see what is wrong with the code, so I would appreciate if you could help me out.

<?php

////Database connection values
$dsn = 'mysql:host=host; dbname=name; charset=utf8';
$db_user = 'username';
$db_pass = 'password';

//Database connection
$db = new PDO($dsn, $db_user, $db_pass); 
$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); // Enable Exception error mode
$db->setAttribute(PDO::ATTR_EMULATE_PREPARES, false); // Use PDO safely = Turn off prepare emulation

// Databse connection check
if($db){
 print "connected to the db " . "<br />";
 }

//Declare values
$name = "";
$email = "";
$userMsg = "";


if ($_POST['name'] != "") {


    $name = $_POST['name'];
    $email = $_POST['email'];

//MySQL SELECT Query    
    $stmt = $db -> prepare ("SELECT * FROM newsletter WHERE email=?");
    $stmt-> bindValue(1, $email);
    $stmt -> execute ();


//Error - No email  
    if (!$email) {

        $userMsg  = '<br /><br /><h4><font color="FF0000">Please type an email address ' . $name . '.</font></h4>';

        } // End email-input check

//Error - Email already in the system       
    else if ($stmt -> rowCount() > 0) {

        $userMsg  = '<br /><br /><h4><font color="FF0000">' . $email . ' is already in the system.</font></h4>';

        } // End Row check

//OK - insert user into database        
     else {

        $insert = $db -> prepare ("INSERT INTO newsletter (name, email, dateTime) VALUES(:name, :email, ,NOW())");
        $insert -> execute(array(':name' => $name, ':email' => $email));                                            

        //Success! - Notify user
        $userMsg  = '<br /><br /><h4><font color="0066FF">Thanks ' . $name . ', you have been added successfully.</font></h4>';

        $name = "";
        $email = "";

            } // End INSERT


}

?>
VALUES(:name, :email, ,NOW())"                            

应该

VALUES(:name, :email, NOW())"

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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