1

I am trying to insert data into a database through php.. Easy enough (I thought). I can't figure out what I am doing wrong. Here is my code:

$DB_HostName = "localhost:8888";
$DB_Name = "Sample";
$DB_User = "root";
$DB_Pass = "root";
$DB_Table = "Check";

$con = mysql_connect($DB_HostName,$DB_User,$DB_Pass) or die(mysql_error()); 
mysql_select_db($DB_Name,$con) or die(mysql_error()); 


$sql =  "INSERT INTO $DB_Table (name) VALUES ('Sally') ";
mysql_query($sql) or die ("Error with Result");

mysql_close($con);  

It gives me an error saying "Error with Result". This means that it must be connecting to the database correctly and everything is working right except for the end part.. What am I missing? If I say (msql_error()) it also does tell me to check the $sql. I can't figure out though what I am typing in wrong.

John Woo
  • 258,903
  • 69
  • 498
  • 492
Zack
  • 871
  • 10
  • 24

2 Answers2

4

escape your database name with backtick

$sql =  "INSERT INTO `$DB_Table` (name) VALUES ('Sally') ";

or

$sql =  "INSERT INTO `" . $DB_Table . "` (name) VALUES ('Sally') ";

CHECK is a MySQL Reserved Keyword.

Community
  • 1
  • 1
John Woo
  • 258,903
  • 69
  • 498
  • 492
  • 1
    Wow.. That annoys me because I've been sitting here for hours trying to figure out why I was getting this error. Thanks man – Zack Nov 20 '12 at 03:28
0

I can't stress this enough, don't use mysql_ functions, that time has gone. Use either mysqli or PDO.

A simple way to check what is wrong with your SQL query is to add an error flag on the end of your die statement mysql_query($sql) or die ("Error with Result<br>".mysql_error());

It appears in your case that check is a constraint used to limit the value range that can be placed in a column. You would need to identify that it is a table using "`":

$sql =  "INSERT INTO `$DB_Table` (name) VALUES ('Sally') ";
Samuel Cook
  • 16,620
  • 7
  • 50
  • 62