gpt4 book ai didi

php - fatal error : Call to a member function prepare() on a non-object on line 16

转载 作者:行者123 更新时间:2023-11-29 08:07:19 25 4
gpt4 key购买 nike

我的网站上有一个注册系统,我正在将所有 mysql 语句更改为 PDO 语句。当我更改它时,我收到此错误: fatal error :在第 16 行调用非对象上的成员函数prepare()

这是我的代码...

<?php

include("sql.php");
require("includes/password.php");

session_start(); //Start session for writing

$errmsg = array(); //Array to store errors

$noterr = array();

$errflag = false; //Error flag

function UniqueID() {
$UID = rand(); //Create unique ID
$check = $db->prepare('SELECT * FROM `users` WHERE `UID` = :UID'); //line 16

$UIDarray = array(
UID => $UID
);

$check->execute($UIDarray);

sql.php...

<?php

ob_start();
session_start();

//database credentials
$dbhost = 'dbhost';
$dbuser = 'dbuser';
$dbpass = 'dbpass';
$dbname = 'dbname';

$db = new PDO("mysql:host=$dbhost;dbname=$dbname", $dbuser, $dbpass);
$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
?>

最佳答案

您的数据库连接 - $db - 超出范围。参见http://www.php.net/manual/en/language.variables.scope.php

您需要将其添加为函数参数

function UniqueID($db) {
^^^

当你调用该函数时

UniqueID($db)

或者将包含内容放入您的函数中

function UniqueID() {
include("sql.php");

或者声明全局

function UniqueID() {
global $db

关于php - fatal error : Call to a member function prepare() on a non-object on line 16,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22446162/

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