使用for循环将数组插入表中

时间:2014-07-25 08:45:55

标签: php mysql arrays database

我试图将数组中的数据行插入到mysql数据库的表中。我是php,mysql的初学者,对它知之甚少。我只是想了解更多。如果你可以尝试一下它会很棒。

我要插入的代码如下:

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;
}

我想使用下面给出的代码插入:

$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");
}

但每次显示都没有添加。请帮助!!

2 个答案:

答案 0 :(得分:3)

更改

INSERT INTO table

INSERT INTO `table`

因为table是一个保留的关键字。如果你使用保留的关键字作为表名或列名,那么你必须将它们包含在反向标记(`)中。最好不要使用任何保留关键字。如果可以的话更改名称然后它将是最佳选择。您可以在这些问题中查看更多

  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

答案 1 :(得分: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";
}