2

I'm new to PHP and databases and when running the following code I keep getting the 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 'Table (input1) VALUES ('test2')' at line 1." The program is intended to get a string from a form and store it in a database.

This is the HTML file:

<html>
<head>
<title>Php Website</title>
</head>

<body>
<form action="index.php" method="POST">
    <p> Input 1: <input type="text" name="input1"> </p>
    <input type="submit" value="Submit">
</form>
</body>
</html>

This is the PHP file:

define('db_name', 'DataTest');
define('db_user', 'root');
define('db_password', '');
define('db_host', 'localhost');

$link = mysql_connect(db_host, db_user, db_password);

if (!$link)
{
die('Could not connect: ' . mysql_error());
}

$db_selected = mysql_select_db(db_name, $link);

if (!$db_selected)
{
die('Cannot use ' . db_name . ': ' . mysql_error());
}

$value = $_POST['input1'];

$sql = "INSERT INTO Table (`input1`) VALUES ('$value')";

if (!mysql_query($sql))
{
die('Error: ' . mysql_error());
}

mysql_close();

?>

<html>
<head>
  <title>Php Website</title>
</head>

<body>
</body>
</html>
user3055501
  • 315
  • 2
  • 5
  • 7

2 Answers2

0

You have an incorrect syntax for your insert:

INSERT INTO Table (`input1`) VALUES ('$value')
             ^ replace table with the table name

The syntax for insert is:

INSERT INTO tableName (`input1`) VALUES ('$value')

If your table is called table, first i would advise you to change that name asap. But if you would have to use it you have to use `table`, with ` around it

Filipe Silva
  • 21,189
  • 5
  • 53
  • 68
0

Table is a reserved word. EIther don't use it as an identifier (i.e. rename your table), or else quote it in backticks:

INSERT INTO `Table` (`input1`) VALUES ('$value')

Warning

  1. Your code is vulnerable to SQL injection. You really should be using prepared statements, into which you pass your variables as parameters that do not get evaluated for SQL. If you don't know what I'm talking about, or how to fix it, read the story of Bobby Tables.

  2. Also, as stated in the introduction to the PHP manual chapter on the mysql_* functions:

    This extension is deprecated as of PHP 5.5.0, and is not recommended for writing new code as it will be removed in the future. Instead, either the mysqli or PDO_MySQL extension should be used. See also the MySQL API Overview for further help while choosing a MySQL API.

Community
  • 1
  • 1
eggyal
  • 122,705
  • 18
  • 212
  • 237