Search code examples
phpmysqlmysql-error-1064

MySQL Insert error


Ok, when trying to insert into the database I'm getting this error

"You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '@email.com, UT, 84505, NOW(), 69.169.186.192)' at line 1"

I can't figure out the problem. Here is the code for my insert statement.

$insert_query = sprintf("INSERT INTO contacts (first_name, last_name, email, state, zip, date, ip) VALUES (%s, %s, %s, %s, %s, NOW(), %s)",
                        $fname,
                        $lname,
                        $email,
                        $state,
                        $zip,
                        $ip);


$result = mysql_query($insert_query, $connection) or die(mysql_error());

My table has the following structure:

    id int(11)                              
    first_name  varchar(100)                                 
    last_name   varchar(100)                             
    email   varchar(100)                                 
    state   varchar(3)                               
    zip int(10)                             
    date    datetime                                
    ip  varchar(255)

Solution

  • You need to quote all the string-type columns in the insert statement. Replace %s with '%s' in the sprintf format.

    Please read about SQL Injection if you haven't done so already.