获取错误 - 致命错误:在

时间:2017-07-27 06:38:49

标签: php

我试图查看相同的问题/答案,但无法弄清楚。

当我访问索引时。它给出了错误

“致命错误:在......中调用成员函数prepare()......”

----------------------------代码是----------------- -

------------- Page1- index.php

<?php
include 'inti_test.php';
$user_id =3;
$user = $getFromUserClass->userData($user_id);
?>

-------------------第2页 - inti_test.php

<?php

   $dsn = 'mysql:host=localhost; dbname=testdb';
    $user = 'root';
    $pass = 'mypass';
    try{
        $PDO = new PDO($dsn, $user, $pass);
    }catch(PDOException $e){
        echo 'Connection error!' .$e->getMessage();
    }
//------------------------- 
class User{
protected $pdo;

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

public function userData($user_id){
$stmt = $this->pdo->prepare("SELECT * FROM `user_detail_master` WHERE 
`user_id`=:user_id");
$stmt->bindParam(":user_id", $user_id, PDO::PARAM_INT);
$stmt->execute();
return $stmt->fetch(PDO::FETCH_OBJ); 
} 
}

//--------------------- 
global $pdo;
session_start();
$getFromUserClass = new User($pdo);

?>

1 个答案:

答案 0 :(得分:0)

像那样

<?php

   $dsn = 'mysql:host=localhost; dbname=testdb';
    $user = 'root';
    $pass = 'mypass';
    global $pdo;
    try{
        $pdo = new PDO($dsn, $user, $pass);
    }catch(PDOException $e){
        echo 'Connection error!' .$e->getMessage();
    }
//------------------------- 
class User{
protected $pdo;

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

public function userData($user_id){
$stmt = $this->pdo->prepare("SELECT * FROM `user_detail_master` WHERE 
`user_id`=:user_id");
$stmt->bindParam(":user_id", $user_id, PDO::PARAM_INT);
$stmt->execute();
return $stmt->fetch(PDO::FETCH_OBJ); 
} 
}

//--------------------- 

session_start();
$getFromUserClass = new User($pdo);

?>