PDO准备错误

时间:2015-04-22 13:15:39

标签: php mysql

public function connect(){
        /*connect to data base change to PDO, for securely*/
        try{
        $connection = new PDO('mysql:host=127.0.0.1;dbname=system', 'root', '' );
        $connection->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
        $connection->setAttribute(PDO::ATTR_EMULATE_PREPARES,false);
        }catch(PDOException $e){
            die('this won\'t work');
        }
    }

    public function insert($table, $fields, $values){
        $fields = implode(", ", $fields);
        $values = implode("','", $values);
        try{
        /*what have i done wrong here??*/
        $stmt = $this->connection->prepare("INSERT INTO $table(ID, $fields) VALUES ('', '$values')");
        $stmt->execute();
        return TRUE;
        }catch(PDOException $j){
            die("Could not send data");
        }
    }
}

错误:在非对象中调用成员函数prepare()。准备就在那里但是为空?

我在这里做错了什么?

1 个答案:

答案 0 :(得分:2)

您没有存储与对象的连接。因此,在您的下一个方法中,连接对象将丢失。试试这个:

  try{
    $this->connection = new PDO('mysql:host=127.0.0.1;dbname=system', 'root', '' );
    $this->connection->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
    $this->connection->setAttribute(PDO::ATTR_EMULATE_PREPARES,false);
    }catch(PDOException $e){
        die('this won\'t work');
    }

我希望有所帮助!