【问题标题】:Using MySQLi prepared statements in PHP, getting "No data supplied for parameters in prepared statement "在 PHP 中使用 MySQLi 准备好的语句,得到“没有为准备好的语句中的参数提供数据”
【发布时间】:2015-02-08 22:38:51
【问题描述】:

我正在尝试更新我的网站以使用准备好的语句,但我不断收到此错误,我似乎无法弄清楚原因。我已经在 Google 和 Stackoverflow 上搜索了一个星期,尝试了所有我找到的东西,但没有解决这个问题。我确定我只是在某个地方误解了一些东西。以下是产生错误的代码:

$query = "INSERT INTO `$table` (type, name, company, amount, currentbalance, interest, startingbalance, term, frequency, entrymonth, entryyear, notes) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)";

echo "Preparing query...";
$addstmt = $db->prepare($query);
echo "(" . $addstmt->errno . ") " . $addstmt->error;
echo "<br>Binding params...";
$addstmt->bind_param('s', empty($type) ? "income" : $type);
$addstmt->bind_param('s', empty($name) ? "" : $name);
$addstmt->bind_param('s', empty($company) ? "" : $company);
$addstmt->bind_param('d', empty($amount) ? 0.0 : $amount);
$addstmt->bind_param('d', empty($currentbalance) ? 0.0 : $currentbalance);
$addstmt->bind_param('d', empty($interest) ? 0.0 : $interest);
$addstmt->bind_param('d', empty($startingbalance) ? 0.0 : $startingbalance);
$addstmt->bind_param('i', empty($term) ? 0 : $term);
$addstmt->bind_param('i', empty($freq) ? 4 : $freq);
$addstmt->bind_param('i', empty($month) ? 0 : $month);
$addstmt->bind_param('i', empty($year) ? 2015 : $year);
$addstmt->bind_param('s', empty($notes) ? "" : $notes);
echo "(" . $addstmt->errno . ") " . $addstmt->error;
echo "<br>Executing statement...";
$result = $addstmt->execute();
echo "(" . $addstmt->errno . ") " . $addstmt->error;

此代码输出以下内容:

Preparing query...(0)
Binding params...(0)
Executing statement...(2031) No data supplied for parameters in prepared statement 

很明显,没有任何东西被插入到数据库中。请帮助我理解我做错了什么。提前谢谢大家。

埃里克

【问题讨论】:

  • 首先为变量设置三元运算符,然后 bind_param() 一次,正如 Barmar 在他的回答中所说的那样。

标签: php mysql mysqli runtime-error prepared-statement


【解决方案1】:

您不会为每个参数重复调用bind_param,而是使用所有参数调用一次。

$addstmt->bind_param('sssddddiiiis', $type, $name, $company, $amount, $currentbalance, $interest, $startingbalance, $term, $freq, $month, $year, $notes);

您也不能在参数中使用表达式。参数绑定到引用,所以你必须给变量。要提供默认值,您必须通过设置变量本身来做到这一点,例如

if (empty($type)) {
    $type = "income";
}

【讨论】:

  • 这是完美的,谢谢。然而,这带来了另一个问题:假设参数的数量是动态的。 (例如,表中的列数并不总是相同)在这种情况下如何使准备好的语句工作?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-07-22
  • 2012-12-01
  • 1970-01-01
  • 2011-06-20
  • 1970-01-01
相关资源
最近更新 更多