【发布时间】:2018-11-19 03:26:28
【问题描述】:
我使用 mysqli prepare 遵循插入函数将值插入数据库。但这并没有给我任何错误,也没有将值插入数据库。有人可以帮我解决问题吗?
我可以打印所有这些数组$fields, $placeholders, $values, $format,而且它们也都显示了正确的值。
public function insert($table, $data, $format) {
global $dbcon;
// Check for $table or $data not set
if (empty($table) || empty($data)) {
return false;
}
// Cast $data and $format to arrays
$data = (array) $data;
$format = (array) $format;
// Build format string
$format = implode('', $format);
$format = str_replace('%', '', $format);
list( $fields, $placeholders, $values ) = $this->prep_query($data);
// Prepend $format onto $values
// array_unshift($values, $format);
// Prepary our query for binding
$stmt = $dbcon->prepare("INSERT INTO {$table} ({$fields}) VALUES ({$placeholders})");
if (false === $stmt) {
die('prepare() failed: ' . htmlspecialchars($mysqli->error));
}
// Dynamically bind values
$bp = call_user_func_array(array($stmt, "bind_param"), array_merge($format, $values));
// $bp = call_user_func_array(array($stmt, 'bind_param'), $this->ref_values($values));
if (false === $bp) {
die('bind_param() failed: ' . htmlspecialchars($stmt->error));
}
// Execute the query
$result = $stmt->execute();
if (false === $result) {
die('execute() failed: ' . htmlspecialchars($stmt->error));
}
// Check for successful insertion
$Insertid = $stmt->insert_id;
return $Insertid;
// if ($stmt->affected_rows) {
// return true;
// }
//
// return false;
}
【问题讨论】:
-
是否返回非零值?
-
如果你想做这样的动态查询构建,我建议你转移到 PDO。必须使用
call_user_func_array()并让变量引用全部正确是一件痛苦的事情。使用 PDO,您可以绑定单个参数和/或使用值数组调用execute() -
@Nick 它没有返回任何东西。
-
您是否逐行跟踪代码?你检查 mysqli 的
$error属性是否存在任何错误?您是否启用了错误报告并查看了 PHP 日志?我认为你最好先做这些,然后再让我们站在你这边。除非您给我们一些线索,否则我们无法获得任何线索。
标签: php mysqli prepared-statement php-5.6