PDO致命错误:在非对象上调用成员函数prepare() [英] PDO Fatal error: Call to a member function prepare() on a non-object

查看:122
本文介绍了PDO致命错误:在非对象上调用成员函数prepare()的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

尝试在数据库中插入数据时出现此错误.我已经搜索了此错误的原因,并且我认为我的代码是正确的,并且我不应该得到该错误.我的代码是这些:

I'm having this error when I try to insert data in my database. I've searched the reasons of this error and I think my codes are right and I'm not supposed to get the error. My codes are these:

config.php

config.php

<?php
class DatabaseConnection{
    public function __construct(){
        try{
        $pdo = new PDO('mysql:host=localhost;dbname=test','root',''); //'mysql:host=host;dbname=dbname','mysqluser','mysqlpassword'
        }
        catch (PDOException $e){
            exit('Database error');
        }   
    }
}
?>

functions.php

functions.php

<?php

require "config.php";

class LoginRegister{
    function __construct(){
        $database= new DatabaseConnection();
    }

    public function registerUser($username,$password,$name,$email){

        global $pdo; //THIS IS THE LINE WITH ERROR
        $query=$pdo->prepare("SELECT id FROM usuarios WHERE nombre_usuario=? AND correo_e=?");
        $query->execute(array($username,$email));
        $num=$query->rowCount();

        if($num==0){
            $query = $pdo->prepare("INSERT INTO usuarios(nombre_usuario,nombre_real,password,correo_e) VALUES (?,?,?,?)");
            $query->execute(array($username,$password,$name,$email));
            return true;
        }else{
            return print "Username or E_mail in use";
        }
    }
}
?>

register.php

register.php

<?php

require_once "functions.php";
$user = new LoginRegister();
?>

...HTML CODE...

<?php
if($_SERVER['REQUEST_METHOD'] == 'POST'){
    $username=$_POST['nombre_usuario'];
    $password=$_POST['password'];
    $name=$_POST['nombre_real'];
    $email=$_POST['correo_e'];

    if(empty($username) or empty($password) or empty($name) or empty($email)){
        echo "Error... Field must not be empty";
    }else{
        $register = $user->registerUser($username,$password,$name,$email);
        if($register){
            echo "Register done <a href='login.php'>Click here</a> for login";
        }else{
            echo "Username or E_mail in use";
        }
    }
}
?>

...HTML CODE...

如您所见,我在registerUser函数中声明了$ pdo变量,除了包含名称,用户名,密码和电子邮件的变量是同一函数的参数之外.

As you can see, I declared the variable $pdo inside the registerUser functions, besides the variables that contain the name, username, password and email are parameters of the same function.

我知道这是几次重复的问题,但是我无法用其他解决方案来解决此错误.

I know this is a several times duplicated question but I cannot solve this error with the solutions in the other ones.

推荐答案

您的代码有几个问题.

在另一个答案中解释了两个,这将使您的代码正常工作(最终这一切都被宠坏了),但这仍然是错误的方法,它将连接到数据库的次数多达您拥有许多对象.

Two were explained in the other answer, which will make your code work (eventually it all was spoiled), but it's still wrong approach, which will connect to database as many times as many objects you have.

以这种方式更改DatabaseConnection类

Change DatabaseConnection class this way

class DatabaseConnection{
    public $pdo;
    public function __construct(){
        $user = 'root';
        $pass = '';
        $dsn  = 'mysql:charset=utf8;dbname=test;host=localhost;charset=utf8';
        $opt  = array(
            PDO::ATTR_ERRMODE            => PDO::ERRMODE_EXCEPTION,
            PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,
        );
        $this->pdo = new PDO($dsn, 'root', '', $opt);
    }
}

以这种方式更改LoginRegister构造函数

Change LoginRegister constructor this way

function __construct($db){
    $this->db= $db;
}

并以这种方式创建register.php

And make register.php this way

require_once "functions.php";
$db = new DatabaseConnection();
$user = new LoginRegister($db->pdo);

,然后在LoginRegister中始终使用$this->db代替$pdo.

and then in LoginRegister use $this->db instead of $pdo all the way.

使$ db连接成为应用程序类的外部服务的主要思想.否则,它将与被鄙视的global相同,只是以另一种形式出现.

The main idea to make $db connection an external service for the application class. Otherwise it will be all the same as despised global, but just in another form.

这篇关于PDO致命错误:在非对象上调用成员函数prepare()的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆