列数与第1行的值计数不匹配 - 但列数是正确的

时间:2012-04-03 18:16:46

标签: php mysql database insert

我有以下代码创建数据库表,然后应该在表中插入6列数据,但它不会将数据插入表中。

我收到以下错误:

列数与第1行的值计数不匹配

下面是应该插入表中的数组数据的代码和print_r:

任何帮助将不胜感激,谢谢。

       // Database Authentication-user, password
          $TableName = 'User_Data';
          $dbh = mysql_connect ("localhost", "username", "password")
          or die ('Cannot connect to the database because: ' . mysql_error());

          mysql_select_db ("database");

       // Creates Database Table if it does not exist
          if(mysql_num_rows(mysql_query("SHOW TABLES LIKE '".$TableName."'")) != 1) {
           mysql_query("CREATE TABLE $TableName(
         id INT NOT NULL AUTO_INCREMENT,
         PRIMARY KEY (id),
         Topic                varchar(300) NOT NULL default '',
         Post_Date            varchar(100) NOT NULL default '',
         Phone_Number         varchar(100) NOT NULL default '',
         Original_Description varchar(2000) NOT NULL default '',
         Alt_Description      varchar(2000) NOT NULL default '',
         Website_Link         varchar(2000) NOT NULL default '') ") or die(mysql_error());
          }

       // Write to MySQL Database
          $queries = array(); 
          for($i=0; $i<count($current_topic_array); $i++) {
             $queries[] = '(
             '.$current_topic_array[$i].',
             '.$post_date_array[$i].',
             '.$phone_array[$i].',
             '.$original_description_array[$i].',
             '.$alt_description_array[$i].',
             '.$website_link_array[$i].'
             )'; 
          }

          echo '<pre>';
          print_r($queries);
          echo '</pre>';

          mysql_query("insert into $TableName (Topic, Post_Date, Phone_Number, Original_Description, Alt_Description, Website_Link)
          values (". implode(',', $queries) . ")") or die(mysql_error());


Array
(
    [0] => (
               'Classic Cars',
               '05-02-2012',
               '777-555-1212',
               'Classic Car show held in Spring of May 2012',
               'Classic Car May 2012',
               'http://website.com/post/864.html'
               )
    [1] => (
               'Classic Cars',
               '07-13-2012',
               '777-555-5412',
               'Classic Car show held in Summer of July 2012',
               'Classic Car July 2012',
               'http://website.com/post/865.html'
               )
    etc...
)

1 个答案:

答案 0 :(得分:0)

如果列是VARCHAR,因此您希望接收字符串值,则需要将值包装在单引号中。最简单的方法是将所有列都设为字符串

mysql_query("insert into $TableName (Topic, Post_Date, Phone_Number, Original_Description, Alt_Description, Website_Link)
      values ('". implode("','", $queries) . "')") or die(mysql_error());

虽然你应该调查PDO,因为它会为你做。

EDIT 尝试重构像这样的代码

$sql = "insert into $TableName (Topic, Post_Date, Phone_Number, Original_Description, Alt_Description, Website_Link)
      values ('". implode("','", $queries) . "')";
mysql_query( $sql ) or die(mysql_error());

然后,您应该能够回显出正在运行的实际查询,以查看问题所在。