Monday, April 25, 2011

Why is this MySQL query failing?

This query keeps failing with

Integrity constraint violation: 1048 Column 'login_name' cannot be null

My insert statement is...

 $insertUserQuery = 'INSERT INTO `users` (
                    `login_name`,
                    `password`, 
                    `first_name`,
                    `last_name`,
                    `company_name`,
                    `company_address`,
                    `country`,
                    `email`,
                    `phone_number`,
                    `agency_type`,
                    `sold_before`,
                    `authorised`,
                    `current_module`
                    )
                    VALUES (
                   :login_name, :login_password, :first_name, :last_name, :company_name, :company_address, :country, :email, :phone_number, :agency_type, :sold_before, 0, 0);';

 $bindings = array(':login_name'      => $loginName,
                   ':login_password'  => sha1($password . Config::PASSWORD_SALT),
                   ':first_name'      => $firstName,
                   ':last_name'       => $lastName,
                   ':company_name'    => $companyName,
                   ':company_address' => $companyAddress,
                   ':country'         => $country,
                   ':email'           => $emailAddress,
                   ':phone_number'     => $phone,
                   ':agency_type'     => null,
                   ':sold_before' => null  
                   );

print_r($bindings);     

 Db::query($insertUserQuery, $bindings);

My Db class can be found here. The print_r() tells me that the array definitely has a value. I had some thoughts...

  • May it have something to do with me using the word 'password' which is also a MySQL function?
  • Does PDO support prepared statements with INSERT in the same fashion as it does with SELECT?
  • Do I need to quote around the values, example ':login_name'

Thank you muchly

From stackoverflow
  • PDO::query doesn't support prepared statement syntax does it? Give PDO::prepare and PDOStatement::execute a read. You probably want something like:

    $insertUserQuery = 'INSERT INTO `users` (`login_name`, ...) ' .
        'VALUES (:login_name, ...);';
    $bindings = array(':login_name' => $loginName, ...);
    $stmt = Db::prepare($insertUserQuery);
    $stmt->execute($bindings);
    

    You can also call $stmt->bindValue() instead of building an array of bindings. I think that explicitly binding each value is a little nicer since you can verify the types right there.

    EDIT: sorry jcinacio, I didn't see that your comment was almost identical until after I posted.

    alex : I think I'm better off ditching my singleton pattern, as I'm putting more abstractions on PDO (which I guess abstracts away MySQL specific commands). Thanks for your answer.

0 comments:

Post a Comment