当我单独运行PDO脚本时它运行得很好但是当我在一个函数中运行它时我得到了这个错误致命错误:在非对象上调用成员函数prepare()。我无法弄清楚它为什么会发生。
$pid = 6;
$custid = 1;
$sql = "SELECT COUNT(*) from signings WHERE pid = ? AND custid = ?";
$stmt = $db->prepare($sql);
$stmt->bindParam(1, $pid, PDO::PARAM_INT);
$stmt->bindParam(2, $custid, PDO::PARAM_STR);
$stmt->execute();
$number_of_rows = $stmt->fetchColumn();
echo $number_of_rows;
$pid = 6;
$custid = 1;
function test($custid,$pid){
$sql = "SELECT COUNT(*) from signings WHERE pid = ? AND custid = ?";
$stmt = $db->prepare($sql);
$stmt->bindParam(1, $pid, PDO::PARAM_INT);
$stmt->bindParam(2, $custid, PDO::PARAM_STR);
$stmt->execute();
$number_of_rows = $stmt->fetchColumn();
echo $number_of_rows;
}
echo test($custid,$pid);
答案 0 :(得分:2)
变量$db
在您的函数中不可见。你需要添加
function test($custid,$pid){
global $db;
[...]
}
在函数内部,或者你应该通过参数:
将db对象传递给你的函数function test($db, $custid,$pid){
[...]
}
另一个好方法是使用工厂模式:
使用静态方法dbFactory创建一个类db,并在需要访问db
时调用它class db {
public static function dbFactory($host, $dbase, $user, $pass) {
$pdo = new PDO("mysql:host=$host;dbname=$dbase", $user, $pass);
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$pdo->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);
return $pdo;
}
}
$db = db::dbFactory('localhost','mydbname','myusername','mypassword');