PDO MySQL insert not working

Discussion in 'PHP' started by gilgil2, Sep 10, 2012.

  1. #1
    Hi I have the following code being used to insert some data into a MySql database, all the error checks etc. are done before and those are fine, and the code returns connected successfully but nothing is put into the database, nor does the database check for duplicate usernames, because if you enter a duplicate username it does not come up as an error.

    So I'm not entirely sure what the problem is, if someone could tell me what the problem is, or at least how to put one of those error things in so it can tell me the problem I would be very grateful.

    $a = md5(uniqid(rand(), true));$username = $_POST['username'];$email = $_POST['email'];$password = $_POST['password'];
    try {$dbname = "xxxx";$dbhost = "xxxxx";$dbuser = "xxxxx";$dbpass ="xxxxx";
            $db=new PDO("mysql:dbname=$dbname;host=$dbhost",$dbuser,$dbpass);        echo 'Connected successfully<br />';     } catch (PDOException $e) {        die ('Connection failed: '.$e->getMessage());    }
        
    
    $sql = "INSERT INTO users (username, email, password, active) VALUES (:username,:email,:password,:active)";
    $q = $db->prepare($sql);
    $q->execute(array(':username'=>$username,':email'=>$email,':password'=>$password,':active'=>$a)); 
                    theme_header('Registration Successful');                echo '<p>Form was filled out correctly</p>';                theme_footer();            }
    PHP:
    Also I know i need to encrypt the password, do I need to escape the Mysql string using PDO? Do I use the same function?

    Thanks
    Gilgil2
     
    gilgil2, Sep 10, 2012 IP
  2. malky66

    malky66 Acclaimed Member

    Messages:
    3,997
    Likes Received:
    2,248
    Best Answers:
    88
    Trophy Points:
    515
    #2
    Try this:

    $username = $_POST['username'];
    $email = $_POST['email'];
    $password = $_POST['password'];
    $sql = "INSERT INTO users (username, email, password, active) VALUES (:username,:email,:password,:active)";
    $q = $db->prepare($sql);
    $q -> bindParam(':username', $username);
    $q -> bindParam(':email', $email);
    $q -> bindParam(':password', $password);
    $q -> bindParam(':active', $a);
    $q->execute();
    theme_header('Registration Successful');
    echo '<p>Form was filled out correctly</p>';
    theme_footer();
    
    Code (markup):
    You don't need to escape anything, the PDO layer does that for you.
     
    Last edited: Sep 11, 2012
    malky66, Sep 11, 2012 IP