Question:
SQL Syntax error in PHP script?
anonymous
2011-08-15 16:25:20 UTC
I get an error from some php code which is trying to insert some data into a MySQL table. Here is the form I am using to capture the data:




Name:

Email:




This file then processes that form:

$con = mysql_connect("localhost","username","password");
mysql_select_db("dbname", $con);

$sql="INSERT INTO `dbname`.`NEWSLETTER` (
`id` ,
`name` ,
`email`
)
VALUES (NULL , '$_POST[name]', '$_POST[email]'";
if (!mysql_query($sql,$con))
{
die('Error: ' . mysql_error());
}
echo "You were added to the EvilDroid Newsletter list.";
mysql_close($con);


This code then returns this error:

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 '' at line 6

Any help will be much appreciated.
Three answers:
Mirox
2011-08-15 16:43:48 UTC
$sql="INSERT INTO NEWSLETTER (name,email)

VALUES

('$_POST[name]','$_POST[email]')";



This is only IF your table is named : NEWSLETTER

and your fields in your NEWSLETTER table are name, and email. The id should auto increment, setup as an identity, so you don't need to add that manually.



IMPORTANT NOTE: I would HIGHLY stress that you sanitize your data. (Make sure it is safe from SQL injection) -> http://en.wikipedia.org/wiki/SQL_injection



You can use.. mysql_real_escape_string()

eg. (Make sure you only use these while your database connection is active)

$sanName = mysql_real_escape_string($_POST["name"]);

$sanEmail = mysql_real_escape_string($_POST["email"]);



Then your $sql assignment would become:



$sql="INSERT INTO NEWSLETTER (name,email)

VALUES

('$sanName','$sanEmail')";
Ratchetr
2011-08-15 16:37:51 UTC
Looks like you are missing a ) in your values clause.



Untested, but I think this fixes it:

VALUES (NULL , '$_POST[name]', '$_POST[email]')";



Added ) between the ' and "
lutz
2016-10-19 05:56:45 UTC
comprise 'closedb.phps'; <-- the 's' should not be interior the record extension could desire to be comprise 'closedb.own abode page'; additionally your submit variables could could desire to get replaced to apply single costs somewhat of double. a minimum of i've got constantly used single costs. $_POST["sOrdered_P"]; replace to $_POST[sOrdered_P'];


This content was originally posted on Y! Answers, a Q&A website that shut down in 2021.
Loading...