在函数内部调用时 PDO 失败

PDO fails when called inside a function

我正在尝试使用一个函数来执行我所有的 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);

尝试关注

$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 传递给您的函数。