开发者

Connecting to MySQL with PHP Gives SQL Sytax Error

I'm new at PHP and SQL, so I was playing around with this table stuff, but it won't work. What's wrong with this script? I get this error:

"Error: You ha开发者_开发技巧ve 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 3"

The PHP script:

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

mysql_select_db($mysql_database, $con);

$sql="INSERT INTO Persons (name, age)
VALUES
('$_POST[name]','$_POST[age])";

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

mysql_close($con)
?>


add Apostrophe

$sql="INSERT INTO Persons (name, age)
VALUES
('$_POST[name]','$_POST[age]')"


As others have pointed out, you missed a single quote just before the closing parenthesis.

Also, you should never use POST values in the fashion:

$sql="INSERT INTO Persons (name, age)
VALUES
('$_POST[name]','$_POST[age]')";

Use this:

$name = mysql_real_escape_string($_POST[name]);
$age = mysql_real_escape_string($_POST[age]);

$sql="INSERT INTO Persons (name, age) VALUES ('$name','$age')";

This is to prevent SQL injection attacks.

EDIT: Take a look at this: https://stackoverflow.com/a/60496/379892 . You'll find more details on preventing SQL injection attacks.


You missed a closing apostrophe:

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


$sql="INSERT INTO Persons (name, age)
VALUES
('$_POST[name]','$_POST[age])";

should be

$sql="INSERT INTO Persons (name, age)
VALUES
('$_POST[name]','$_POST[age]')";


Add this part in and see what result you get:

$db_selected = mysql_select_db($mysql_database, $con);
if (!$db_selected) {
  die ('Can\'t use foo : ' . mysql_error());
}


Also, shouldn't it be like this?

$sql="INSERT INTO Persons (name, age) VALUES ('{$_POST['name']}','{$_POST['age']}')";

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜