在非对象上调用成员函数query()

时间:2016-07-10 22:23:29

标签: php mysqli

我在尝试执行插入查询时遇到了这个致命错误。

此处DaoUsuario.php第27行 - > $banco->query($queryInsert);

我的代码:

的index.php

<?php

  if($_POST['botao']){
    $nome = $_POST['nome'];
    $sobrenome = $_POST['sobrenome'];
    $cpf = $_POST['cpf'];
    $usuario = $_POST['usuario'];
    $senha = $_POST['senha'];

    $u = new Usuario;
    $u->setNome($nome);
    $u->setSobrenome($sobrenome);
    $u->setCpf($cpf);
    $u->setUsuario($usuario);
    $u->setSenha($senha);

    $daoUsuario = new DaoUsuario;
    $daoUsuario->insertUsuario($u);
  }
?>

DaoUsuario.php

<?php

  include_once './models/Usuario.php';
  include_once 'connectionFactory.php';

  class DaoUsuario {

    private $dbh;

    function DaoUsuario(){
      $this->dbh = new ConnectionFactory;
    }

    function insertUsuario(Usuario $u) {
      mysqli_report(MYSQLI_REPORT_STRICT);

      $nome = $u->getNome();
      $sobrenome = $u->getSobrenome();
      $cpf = $u->getCpf();
      $usuario = $u->getUsuario();
      $senha = $u->getSenha();

      $queryInsert = "insert into usuario (nome, sobrenome, cpf, usuario, senha) values (
        $nome, $sobrenome, $cpf, $usuario, $senha)";
      echo $queryInsert;
      $banco = $this->dbh->getDbh();
      $banco->query($queryInsert);
      $this->dbh->fechaConexao();
      echo "Inserido com sucesso!";
    }
  }
?>

connectionFactory.php

class ConnectionFactory {
#atributos..
private $servidor = 'localhost';
private $usuario = 'root';
private $senha = 'admin';
private $bd = 'sistemaloja';
private $dbh;

#métodos..
public function abreConexao(){
  mysqli_report(MYSQLI_REPORT_STRICT);
  error_reporting(!E_NOTICE);

  try{
    $this->dbh = new mysqli_connect($this->servidor, $this->usuario, $this->senha, $this->bd);
  }catch (Exception $e){
    echo ("Erro ao conectar!");
    echo ("Mensagem: " . $e->getMessage());
    exit;
  }
}

public function fechaConexao(){
  $this->dbh->close();
}

有关如何解决此问题的任何想法?此外,我知道我没有使用所有面向对象的概念,因为我正在学习。

1 个答案:

答案 0 :(得分:0)

所以看起来abreConexao()从未被调用过。那为什么没有分配给$ dbh,并使$ banco成为一个空变量?

可能是,在DaoUsuario课程中添加一行:

function DaoUsuario(){
      $this->dbh = new ConnectionFactory;
      $this->dbh->abreConexao();
    }

或者在ConnectionFactory类中添加一个构造函数:

function ConnectionFactory(){
     $this->abreConexao(); 
 }