【问题标题】:insert an array into table using for loop使用for循环将数组插入表中
【发布时间】:2014-09-17 01:35:31
【问题描述】:

我正在尝试将数组中的数据行插入到 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");
}

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

【问题讨论】:

标签: php mysql arrays database


【解决方案1】:

改变

INSERT INTO table

INSERT INTO `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

【讨论】:

    【解决方案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";
    }
    

    【讨论】:

      猜你喜欢
      • 2015-05-11
      • 1970-01-01
      • 1970-01-01
      • 2015-02-13
      • 1970-01-01
      • 1970-01-01
      • 2012-02-18
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多