简体   繁体   中英

mySQL query syntax error?

I have contact form at my wordpress site which is delivered by ajax, and sent to my mail. I also wanted to save the results in a database so I wrote this query, but it gives me and syntax error, but I can't find anything wrong in this code:

<?php 
$con = mysql_connect("localhost","username","password");
if (!$con)
  {
  die('Could not connect: ' . mysql_error());
  }

mysql_select_db("u31272B3", $con);

$sql="INSERT INTO wp_contactform (Nimi, Puhelin, E-mail, Viesti, IP, Day)
VALUES
('$_POST[Nimi]','$_POST[Puhelin]','$_POST[Sposti]','$_POST[Tiedot]','$_POST[Gotcha]','$_POST[Day]')";

if (!mysql_query($sql,$con))
  {
  die('Error: ' . mysql_error());
  }
echo "1 record added";

mysql_close($con);

?>

The jquery script that sends it works, and the mail is sent, but this doesn't save.

Quote the column name E-mail with backticks (`). MySQL is interpreting this in two parts at the moment.

Note also, (as per my comment) that your code is wide open to SQL injection attacks. It is much better to use properly parameterised SQL queries.


SQL injection example:

"INSERT INTO table (field) VALUE ('$_POST[var]')"

If you post the value "'; DROP TABLE table; --" then you have a valid SQL string that inserts an empty string, then attempts to drop the table. Substitute whatever harmful statement you want.

and also you should use mysql_real_escape_string() or prepared statements. if your query data have any special characters it can blow your query it also help you from sql injection too.

http://php.net/mysql_real_escape_string http://php.net/pdo

Your SQL request should be written as below:

$sql = "INSERT INTO wp_contactform (`Nimi`, `Puhelin`, `E-mail`, `Viesti`, `IP`, `Day`)
        VALUES
        ('$_POST[Nimi]','$_POST[Puhelin]','$_POST[Sposti]','$_POST[Tiedot]','$_POST[Gotcha]','$_POST[Day]')"

SQL fields using non-alphanumeric characters have to be escaped with backticks ( ` )

This should work

<?php
$con = mysql_connect("localhost", "username", "password");
if(!$con){
    die('Could not connect: '.mysql_error());
}

mysql_select_db("u31272B3", $con);

$sql = "INSERT INTO wp_contactform (`Nimi`, `Puhelin`, `E-mail`, `Viesti`, `IP`, `Day`)
VALUES
('".mysql_real_escape_string($_POST['Nimi'])."','".
   mysql_real_escape_string($_POST['Puhelin'])."','".
   mysql_real_escape_string($_POST['Sposti'])."','".
   mysql_real_escape_string($_POST['Tiedot'])."','".
   mysql_real_escape_string($_POST['Gotcha'])."','".
   mysql_real_escape_string($_POST['Day'])."')";

if(!mysql_query($sql, $con)){
    die('Error: '.mysql_error());
}
echo "1 record added";

mysql_close($con);

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