我正在尝试使用一个函数来执行我的所有 PDO 查询。我在使用该函数时遇到 500 错误。如果我不使用该函数,我能够成功执行代码。您会注意到下面的工作代码块和非工作代码块之间的唯一区别是函数的使用。为什么在函数内部调用代码时会失败?作品:try { $conn = new PDO($dsn, $username, $password, $options);}catch (PDOException $e){ echo "Connection failed: " . $e->getMessage();}$info = array();$info['fname'] = $_POST['fname'];$info['lname'] = $_POST['lname'];$info['email'] = $_POST['email'];$info['password'] = password_hash($_POST['password'], PASSWORD_DEFAULT);$info['datecreated'] = date("Y-m-d H:i:s");$sql = "INSERT INTO Users (fname, lname, email, password, datecreated)VALUES (:fname, :lname, :email, :password, :datecreated)";try { $stmt=$conn->prepare($sql); $stmt->execute($info);}catch (PDOException $e){ echo $sql . "PDO query failed: <br>" . $e->getMessage();}不起作用try { $conn = new PDO($dsn, $username, $password, $options);}catch (PDOException $e){ echo "Connection failed: " . $e->getMessage();}$info = array();$info['fname'] = $_POST['fname'];$info['lname'] = $_POST['lname'];$info['email'] = $_POST['email'];$info['password'] = password_hash($_POST['password'], PASSWORD_DEFAULT);$info['datecreated'] = date("Y-m-d H:i:s");$sql = "INSERT INTO Users (fname, lname, email, password, datecreated)VALUES (:fname, :lname, :email, :password, :datecreated)";function pdoquery ($sql, $info){ try { $stmt=$conn->prepare($sql); $stmt->execute($info); } catch (PDOException $e) { echo $sql . "PDO query failed: <br>" . $e->getMessage(); }}pdoquery($sql,$info);
1 回答
慕慕森
TA贡献1856条经验 获得超17个赞
尝试以下
$info = array();
$info['fname'] = $_POST['fname'];
$info['lname'] = $_POST['lname'];
$info['email'] = $_POST['email'];
$info['password'] = password_hash($_POST['password'], PASSWORD_DEFAULT);
$info['datecreated'] = date("Y-m-d H:i:s");
$sql = "INSERT INTO Users (fname, lname, email, password, datecreated)
VALUES (:fname, :lname, :email, :password, :datecreated)";
function pdoquery ($sql, $info, $conn){
$stmt=$conn->prepare($sql);
$stmt->execute($info);
return $stmt;
}
pdoquery($sql,$info, $conn);
简而言之,您忘记传递$conn给您的函数。
- 1 回答
- 0 关注
- 97 浏览
添加回答
举报
0/150
提交
取消