【问题标题】:Mysqli bind parameters not workingMysqli绑定参数不起作用
【发布时间】:2017-12-08 15:50:31
【问题描述】:

我正在尝试使用准备好的语句在数据库中输入数据。未准备的语句有效,但此准备好的语句不起作用。我不知道为什么。 准备好的版本:

$stmt = $mysqli->prepare("INSERT INTO videos (file_name, upload_by, date, path) 
VALUES (?, ?, ?, ?)");
$stmt->bind_param('ssss', $newstring, $id, $date->format('Y-m-d'), $location);
$stmt->execute();

未准备的版本:

  $sql = "INSERT INTO videos (file_name, upload_by, date, path) VALUES ('$newstring', '$id', '
          $date', 'Nominator/$location$newstring')";
  mysqli_query($mysqli, $sql);

【问题讨论】:

  • 正确 $stmt-execute();它必须是 $stmt->execute();
  • 那是错误的。它仍然无法正常工作。
  • 单独给出$date,然后检查。同时添加表结构。
  • 取消工作日期->format('Y-m-d')。当我试图弄清楚这一点时,我已经把它放在那里了。

标签: php mysqli prepared-statement bindparam


【解决方案1】:

$stmt-execute(); 替换为$stmt->execute();

另外,不要在查询中使用datepath。用其他名称重命名它们,例如 date1path1

像下面这样更新您的查询肯定会起作用(离线测试):

<?php
$mysqli = new mysqli('localhost', 'root', '', 'test2'); 

if ($mysqli->errno) {
printf("Connect failed: %s\n", $mysqli->error);
exit();
}

$stmt = $mysqli->prepare("INSERT INTO videos (file_name, upload_by, date1, path1) VALUES (?, ?, ?, ?)");
$stmt->bind_param('ssss', $file_name, $upload_by, $date1, $path1);
$date1 = date("Y-m-d");
$file_name = "test.jpg";
$upload_by = "amit";
$path1 = "test";
if ($result = $stmt->execute()){
echo "success";
$stmt->free_result();
} else {
echo "error";
}
$stmt->close();
?>

【讨论】:

  • 已完成但仍无法正常工作。其中一个变量是否会导致问题。 $location = "Nominator/uploads/".$newstring; 这是我怀疑可能是位置变量
  • 尝试不带日期。并告诉我你的联系。您正在尝试准备好的查询?
  • 这是导致问题的 $date 变量。非常感谢!
  • 同时重命名数据库和代码中的日期和路径变量。我发现它们不工作。
  • 检查我已离线测试的更新答案。最好保持变量名与表中的列名相同。
【解决方案2】:

你绑定了你的参数两次,如果你只使用?,不要再次绑定参数直接执行。

 //Prepare your query first
 $stmt = $mysqli->prepare("INSERT INTO videos (file_name, upload_by, date, path) 
    VALUES (?, ?, ?, ?)");

//Just pass your argument and execute directly without binding the parameter (The parameter is binded already)
$stmt->execute('ssss', $newstring, $id, $date->format('Y-m-d'), $location);

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-10-01
    • 2010-12-27
    • 2012-03-23
    • 1970-01-01
    • 2010-12-03
    • 2012-08-04
    • 1970-01-01
    相关资源
    最近更新 更多