注意:未定义的变量:obj in

时间:2016-11-03 01:43:13

标签: php mysql class object

当我准备$sql时,我收到错误“Notice: Undefined variable: obj in..

member.php

<?php   
require_once('database.php');
$obj = new Database;
$obj->getConnection();
class Member{

private $username;
private $userpassword;

public function regist(){

if(isset($_POST['action'])&&$_POST['action']=='insert'){
try{

    $sql = "INSERT INTO userData(username,password)VALUES(:username,:password)";
    $stmh = $obj->prepare($sql);//the error occour here
    $stmh -> bindValue('username',$_POST['username'],PDO::PARAM_STR);
    $stmh -> bindValue('password',password_hash($_POST['userpassword'],PASSWORD_DEFAULT),PDO::PARAM_STR);
    $stmh -> execute();

    echo "登録しました<br>";
        }catch(PDOExcetion $e){
            echo "error ".$e->getMessage();
        }
    }

}

public function login(){
    $sql = "SELECT * FROM userData WHERE username=:usrname";
    $stmh =$obj->prepare($sql);//the error occour here
    $stmh ->bindValue(':usrname',$_POST['username'],PDO::PARAM_STR);
    $stmh->execute();
    $row = $stmh->fetch(PDO::FETCH_ASSOC);
    if($row['username'] == false){
        echo"login fail";
        exit;
    }
    $hash = $row['password'];
    if (false === password_verify($_POST['userpassword'],$hash)){
        echo"login fail";
        exit;
    }
   }
}

database.php中 我只是创建数据库类,我想使用受保护的$pdo,所以我创建getConnection()函数并返回$pdo。所以我认为我只是创建一个像$obj=new Database(); $obj->getConnection();这样的对象然后我可以访问$pdo变量。但它不起作用。错误发生在“member.php”之上。请帮忙

<?php
class Database{

protected $pdo;

public function __construct()
{
    $this->db_connect();
}

private function db_connect()
{
    $servername = "localhost";
    $username = "abc";
    $password = "abc";
    $dbname = "mydb";
    try
    {
      $this->pdo = new PDO("mysql:host=$servername;dbname=$dbname", $username, $password);
      $this->pdo->setAttribute(PDO::ATTR_ERRMODE,PDO::ERRMODE_EXCEPTION);
      $this->pdo->setAttribute(PDO::ATTR_EMULATE_PREPARES,false);
    }catch(PDOException $e)
        {
        die("error connection ".$e->getMessage());
        }
}
public function getConnection()
{   
    return $this->pdo;
}   
  }
  ?>

1 个答案:

答案 0 :(得分:0)

在任何事物之前在函数中添加global $obj