mysqli在foreach循环中将多行插入表中

时间:2013-09-15 04:25:13

标签: php mysqli insert-into

好吧,我的代码出现了问题:

$db = new mysqli("localhost", "db_username", "db_password", "db_name");

if (mysqli_connect_errno())
{
    printf("Connect failed: %s\n", mysqli_connect_error());
    exit();
}

$cdfi_articles = "CREATE TABLE cdfi_articles (
  id_article int(10) unsigned NOT NULL auto_increment,
  title varchar(255) NOT NULL default '',
  body text NOT NULL,
  section smallint(5) unsigned NOT NULL default '0',
  time int(10) unsigned NOT NULL default '0',
  views int(10) unsigned NOT NULL default '0',
  visible tinyint(3) NOT NULL default '1',
  PRIMARY KEY (id_article),
  KEY section (section),
  KEY visible (visible)
) ENGINE=MyISAM;";

$cdfi_sections = "CREATE TABLE cdfi_sections (
  id_section int(10) unsigned NOT NULL default '0',
  section_name varchar(255) NOT NULL default '',
  section_order smallint(5) unsigned NOT NULL default '0',
  PRIMARY KEY (id_section),
  KEY section_order (section_order)
) ENGINE=MyISAM;";

if (!mysqli_query($db, $cdfi_articles))
    printf("Error: %s\n", mysqli_error($db));

if (!mysqli_query($db, $cdfi_sections))
    printf("Error: %s\n", mysqli_error($db));

$sections = array('Latest News', 'Commentary', 'Impact', 'Opportunities', 'Policy', 'Events', 'People', 'Market', 'Careers');

foreach($sections as $key => $value)
{
    var_dump(mysqli_error($db));
    $stmt = mysqli_prepare($db, "INSERT INTO cdfi_sections VALUES (?, ?)");
    mysqli_stmt_bind_param($stmt, 'si', $value, $key);
    mysqli_stmt_execute($stmt);
    mysqli_stmt_close($stmt);

}

mysqli_close($db);

我收到此错误:

  

警告:mysqli_stmt_bind_param()期望参数1为   mysqli_stmt,第44行的filepath.php中给出的布尔值

我在这里使用php.net页面作为example
        var_dump(mysqli_error($db));为第一个循环返回string(0) "",之后每个循环都会返回string(47) "Column count doesn't match value count at row 1"

问题出在哪里?

2 个答案:

答案 0 :(得分:2)

由于错误,

mysqli_prepare返回false。使用var_dump(mysqli_error($db));来确定特定错误是什么。我怀疑你的$db是问题所在,或者表格不存在。

此外,使用预处理语句,您应该在循环外运行prepare,然后可以在每次迭代时使用不同的参数执行它,这将为您提供性能改进。

答案 1 :(得分:0)

我提供了一些示例代码,其中包含一些有效的错误检查。您报告的错误是由于MySQL调用中发生问题,并且如果没有正确的错误检查,您的代码将无法检测到错误的真正原因。

请注意,我已经颠倒了提供给mysqli_statement的值的顺序,因为您在代码中使用它们的顺序将按照section_name, section_id的顺序向数据库提供值,与您的顺序相反他们在你的桌子上。我还从循环中移除了preparebindclose来电。

此代码适用于我的测试服务器,并在适当的位置报告错误。将其用作模板。

<?php

$db = mysqli_connect('dbhost','dbuser','dbpass','dbname'); 
$sections = array('Latest News', 'Commentary', 'Impact', 'Opportunities', 'Policy', 'Events', 'People', 'Market', 'Careers');

if (($stmt = mysqli_prepare($db, "INSERT INTO cdfi_sections VALUES (?, ?)")) === false) {
  die(mysqli_error($db));
}

$idx = 0;
$text = '';

if (mysqli_stmt_bind_param($stmt, 'is', $idx, $text) === false) {
  die(mysqli_stmt_error($stmt));
} 

foreach($sections as $key => $value)
{
  $idx = $key;
  $text = $value;
  echo "idx:$idx, text:$text";
  if (mysqli_stmt_execute($stmt) === false) {
    die(mysqli_stmt_error($stmt));
  }
}

mysqli_stmt_close($stmt);
?>