0

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 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 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)
?>
Alex Gittemeier
  • 5,224
  • 30
  • 55
IceCat
  • 39
  • 1
  • 5

6 Answers6

4

add Apostrophe

$sql="INSERT INTO Persons (name, age)
VALUES
('$_POST[name]','$_POST[age]')"
Haim Evgi
  • 123,187
  • 45
  • 217
  • 223
1

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.

Community
  • 1
  • 1
Naweed Chougle
  • 500
  • 10
  • 31
0

You missed a closing apostrophe:

('$_POST[name]','$_POST[age]')";
Luke Stevenson
  • 10,357
  • 2
  • 26
  • 41
  • 1
    Oh, and insert standard comments regarding sanitisation of form input when working with databases, SQL Injection, and all that. – Luke Stevenson Nov 17 '10 at 13:00
0
$sql="INSERT INTO Persons (name, age)
VALUES
('$_POST[name]','$_POST[age])";

should be

$sql="INSERT INTO Persons (name, age)
VALUES
('$_POST[name]','$_POST[age]')";
jyggen
  • 31
  • 1
  • 6
0

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());
}
Matt Asbury
  • 5,644
  • 2
  • 21
  • 29
0

Also, shouldn't it be like this?

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