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条)

报告相同问题?

悬赏问题

  • ¥15 乌班图ip地址配置及远程SSH
  • ¥15 怎么让点阵屏显示静态爱心,用keiluVision5写出让点阵屏显示静态爱心的代码,越快越好
  • ¥15 PSPICE制作一个加法器
  • ¥15 javaweb项目无法正常跳转
  • ¥15 VMBox虚拟机无法访问
  • ¥15 skd显示找不到头文件
  • ¥15 机器视觉中图片中长度与真实长度的关系
  • ¥15 fastreport table 怎么只让每页的最下面和最顶部有横线
  • ¥15 R语言卸载之后无法重装,显示电脑存在下载某些较大二进制文件行为,怎么办
  • ¥15 java 的protected权限 ,问题在注释里