gpt4 book ai didi

php - "Call to a member function prepare()"背后的逻辑

转载 作者:行者123 更新时间:2023-11-29 11:32:30 35 4
gpt4 key购买 nike

我正在编写一个函数来在执行任何操作之前检查数据库中的记录,但我收到错误 Call to a member function prepare()我不太明白。我已经挣扎了很长一段时间了,我真的很感谢一些帮助

问题应该出在 prepare() 上在第 19 行

<?php
$dsn = "xxx"; // Database Source Name
$username="xxx"; // User with acress to database. Root is MySQL admin.
$password="xxx"; //The user password.

try {
$conn = new PDO($dsn, $username, $password);
$conn ->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
} catch(PDOException $e) {
echo "Connection failed: ".$e->getMessage();
}

//------------------------ Does the category already exist? -------------------------
function checkuser($fbid,$fbfname,$fblname,$femail) {

$sql="SELECT COUNT(*) AS subjectcount FROM Users WHERE Fuid=:Fuid";

try {
$stmt = $conn->prepare($sql);
$stmt->bindValue(":Fuid",$_SESSION['FBID'], PDO::PARAM_INT);
$stmt->execute();
$row = $stmt->fetch(PDO::FETCH_ASSOC);
$subjectcount=$row["subjectcount"];
} catch (PDOException $e) {
echo "Server Error - try again!".$e->getMessage();
}

//------------------------ If it dosn't, insert it -------------------------
if ($subjectcount==0) {

而且我很难调试,因为我不太明白这个错误的原因。

我将代码更新为

<?php
$dsn = "xxx"; // Database Source Name
$username="xxx"; // User with acress to database. Root is MySQL admin.
$password="xxx"; //The user password.

try {
$conn = new PDO($dsn, $username, $password);
$conn ->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
} catch(PDOException $e) {
echo "Connection failed: ".$e->getMessage();
}

//------------------------ Does the category already exist? -------------------------
function checkuser($fbid,$fbfname,$fblname,$femail) {
global $conn;
$sql="SELECT COUNT(*) AS subjectcount FROM Users WHERE Fuid=:Fuid";

try {
$stmt = $conn->prepare($sql);
$stmt->bindValue(":Fuid",$_SESSION['FBID'], PDO::PARAM_INT);
$stmt->execute();
$row = $stmt->fetch(PDO::FETCH_ASSOC);
$subjectcount=$row["subjectcount"];
} catch (PDOException $e) {
echo "Server Error - try again!".$e->getMessage();
exit;
}

//------------------------ If it dosn't, insert it -------------------------
if ($subjectcount==0) {

最佳答案

我猜完整的错误消息是:

Fatal error: Call to a member function prepare() on a non-object

对吗?

您正在调用变量$conn的成员函数(=类实例成员的函数)prepare,该变量未在您的作用域中声明checkuser 函数,它是在外部声明的(在全局范围内)!

要将其“导入”到您的函数中以便您可以访问它,请将此行放在函数的顶部:

global $conn;

此外,您似乎没有启用完整的错误报告,否则您会在 fatal error 之前看到此错误,从而为您提供另一条线索:

Notice: Undefined variable: conn

(顺便说一句,在 catch block 中输出数据库错误消息后,您应该 exit; - 否则您将打印错误但继续其余部分,使用不存在的数据库连接!)

关于php - "Call to a member function prepare()"背后的逻辑,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37171435/

35 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com