duanquan1876 2015-10-02 04:14
浏览 44
已采纳

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

<?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

<?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

<?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...

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.

  • 写回答

4条回答 默认 最新

  • dtcmadj31951 2015-10-02 04:35
    关注

    There are several problems with your code.

    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.

    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);
        }
    }
    

    Change LoginRegister constructor this way

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

    And make register.php this way

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

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

    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.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(3条)

报告相同问题?

悬赏问题

  • ¥50 导入文件到网吧的电脑并且在重启之后不会被恢复
  • ¥15 (希望可以解决问题)ma和mb文件无法正常打开,打开后是空白,但是有正常内存占用,但可以在打开Maya应用程序后打开场景ma和mb格式。
  • ¥20 ML307A在使用AT命令连接EMQX平台的MQTT时被拒绝
  • ¥20 腾讯企业邮箱邮件可以恢复么
  • ¥15 有人知道怎么将自己的迁移策略布到edgecloudsim上使用吗?
  • ¥15 错误 LNK2001 无法解析的外部符号
  • ¥50 安装pyaudiokits失败
  • ¥15 计组这些题应该咋做呀
  • ¥60 更换迈创SOL6M4AE卡的时候,驱动要重新装才能使用,怎么解决?
  • ¥15 让node服务器有自动加载文件的功能