1

I am trying to insert rows of data in an array into a table in mysql database. I am a beginner in php, mysql and have very little knowledge about it. I just want to learn more. If you can give this a try It would be great.

The code which i want to insert is below:

for($x=0; $x<2; $x++)
{
    $data[$x]['title']          = $titleQuery->item($x)->nodeValue;
    $data[$x]['titleHrefQuery'] = $titleHrefQuery->item($x)->nodeValue;
    $data[$x]['food']           = $foodQuery->item($x)->nodeValue;
    $data[$x]['locality']       = $localityQuery->item($x)->nodeValue;
    $data[$x]['rating']         = $ratingQuery->item($x)->nodeValue;
    $data[$x]['cost']           = $costQuery->item($x)->nodeValue;
}

I am tring to insert using the code given below:

$query = "INSERT INTO table (`title`, `link`, `food`, `locality`, `rating`, `cost`) VALUES 
        ('" . $titleQuery->item($x)->nodeValue . "', 
         '".$titleHrefQuery->item($x)->nodeValue."', 
         '".$foodQuery->item($x)->nodeValue."', 
         '".$localityQuery->item($x)->nodeValue."', 
         '".$ratingQuery->item($x)->nodeValue."', 
         '".$costQuery->item($x)->nodeValue."')";

$result = mysql_query($query);

if($result)
{
    echo ("Success");
} 
else
{
    echo ("Not added");
}

But every time it shows not added. please help!!

Mohit S
  • 13,723
  • 6
  • 34
  • 69
shivam
  • 383
  • 8
  • 22

2 Answers2

3

Change

INSERT INTO table

to

INSERT INTO `table`

Because table is a reserved keyword.And if you are using reserved keywords as table name or column name then you must enclose them in back-ticks (`).And its better not to use any reserve keyword.So if you can change the name then it will be the best choice.You can check for more in these questions

  1. How do I escape reserved words used as column names? MySQL/Create Table

  2. Can we have the table name as "option" in MySQL?

  3. H2 database column name "GROUP" is a reserved word

Community
  • 1
  • 1
웃웃웃웃웃
  • 11,829
  • 15
  • 59
  • 91
2
"INSERT INTO table...." should be "INSERT INTO `table`..."

Try to avoid mysql key names as table name or field name it would help you in writing better sql queries.

Use following line to see mysql error so can you easily track the reason why you are getting error - 

if($result)
{   
     echo ("Success");
}
else
{
    echo ("Not added");
    echo mysql_errno($link) . ": " . mysql_error($link). "\n";
}
GKS
  • 106
  • 5