Alexandr
Alexandr

Reputation: 41

Warning: PDOStatement::execute(): SQLSTATE[HY093]: Invalid parameter number: parameter was not defined in C:\wamp\www\PDO.php on line 24

Today, I was trying my code and I got this error : parameter was not defined... Please, help me:

    <?php
    $user = 'dbuser';
    $pass = 'pwd';
    $db = new PDO( 'mysql:host=localhost;
dbname=registration', $user, $pass );
    $form = $_POST;
    $firstname = $form[ 'firstname' ];
    $lastname = $form[ 'lastname' ];
    $username = $form[ 'username' ];
    $email = $form[ 'email' ];
    $password = $form[ 'password1' ];
    $dateofbirth = $form[ 'dateofbirth' ];
    $monthofbirth = $form[ 'monthofbirth' ];
    $yearofbirth = $form[ 'yearofbirth' ];
    $gender = $form[ 'gender' ]; 
    $sql = "INSERT INTO members ( firstname, lastname, username, email,
password, dateofbirth, monthofbirth, yearofbirth, gender ) 
VALUES ( :firstname, :lastname, :username, 
:email, :password1, :dateofbirth, :monthofbirth, :yearofbirth,
:gender )";
    $query = $db->prepare( $sql );
    $query->execute( array( ':firstname'=>$firstname, ':lastname'=>      $lastname, 
':username'=>$username, ':email'=>$email, ':password'=>$password, 
':dateofbirth'=>$dateofbirth, ':monthofbirth'=>$monthofbirth, 
':yearofbirth'=>$yearofbirth, ':gender'=>$gender ) );
    $result = $query->execute( array( ':firstname'=>$firstname,                                                 ':lastname'=>$lastname, 
':username'=>$username, ':email'=>$email, ':password'=>$password, 
':dateofbirth'=>$dateofbirth, ':monthofbirth'=>$monthofbirth, 
':yearofbirth'=>$yearofbirth, ':gender'=>$gender ) );
    if ( $result ){
    echo "<p>Thank you. You have been registered</p>";
    } else {
    echo "<p>Sorry, there has been a problem inserting your details.         Please contact admin.</p>";

} ?>

Upvotes: 0

Views: 482

Answers (1)

Elias Van Ootegem
Elias Van Ootegem

Reputation: 76413

In the query string you're passing to PDO::prepare you have this parameter:

:email, :password1

But the array you're passing to PDOStatement::execute doesn't have a :password1 key, it has a :password key instead. It's a simple typo: fix either one or the other.

It might be a good idea to sanitize the actual submitted data before storing it in the DB, though. Things like an email address are easily verified using something like:

if (!filter_var($email, FILTER_VALIDATE_EMAIL))
{
    printf(
        '%s is not a valid email address, please fill in correct values',
         $email
    );
    //rebuild form, and return response to client
}
else
{
    //carry on validating data, eventually insert it in the DB
}

It's also important not to forget to check the post params using isset, if you don't your code can, and will, generate a lot of notices

Upvotes: 3

Related Questions