Connect to DB with PHP Class isn't working when try to retrieve results

匿名 (未验证) 提交于 2019-12-03 09:13:36

问题:

Good morning.

I'm trying to make a DB class to connect and retrieve results from my DB. So, I think with the class is everything good. But, the results won't appear.

Here is my DB class:

<?php class Conexao {  var $host    = "localhost"; var $usuario = "root"; var $senha = "xxxxxx"; var $banco = 'restaurante'; private $mysqli;  public function Abrir() { $this->mysqli = new mysqli($this->host, $this->usuario, $this->senha, $this->banco); }  public function Fechar() { $this->mysqli->close(); } }  class Comando { public function Executar($sql) { $con = new Conexao(); $con->Abrir();  $re = $con->mysqli->query($sql); $con->Fechar(); return $re; } } ?> 

And here is where I'm trying to retrieve the results:

<?php  $queryMesasAtivas = Comando::Executar('SELECT * FROM mesas WHERE status =1 AND numero !="'.$_SESSION["mesa"].'"');  if ($queryMesasAtivas->num_rows > 0) {    while ($rowMesasAtivas = $queryMesasAtivas->fetch_assoc()) { echo "<option value='".$rowMesasAtivas['numero']."'>Mesa ".$rowMesasAtivas['numero']."</option>"; } } else { echo '<option>Nenhuma mesa ativa</option>'; }   ?> 

I tried some modifications but, nothing changes. Everytime it's still not working. What's wrong?

回答1:

As the Comando::Executar is not static, but rather declared as public function..., you will have to do something such as:

$comando = new Comando();  $queryMesasAtivas = $comando->Executar('SELECT * FROM mesas WHERE status =1 AND numero !="'.$_SESSION["mesa"].'"');  if ($queryMesasAtivas->num_rows > 0) {      while ($rowMesasAtivas = $queryMesasAtivas->fetch_assoc()) {         echo "<option value='".$rowMesasAtivas['numero']."'>Mesa ".$rowMesasAtivas['numero']."</option>";     } } else {     echo '<option>Nenhuma mesa ativa</option>'; } 

Or declare the method as static, namely:

public static function Executar($sql) {     $con = new Conexao();     $con->Abrir();     $re = $con->mysqli->query($sql);     $con->Fechar();     return $re; } 

And then you can use the double colon (::) syntax:

$queryMesasAtivas = Comando::Executar('SELECT * FROM mesas WHERE status =1 AND numero !="'.$_SESSION["mesa"].'"'); 

I would suggest not calling an open and close every time you run a query, but rather a class like this:

class Conexao {     private $link;      public function __construct($host = null, $username = null, $password = null, $dbName = null)     {         $this->link = mysqli_init();         $this->link->real_connect($host, $username, $password, $dbName) or die("Failed to connect");     }      public function __destruct()     {         $this->link->close();     }      public function Query($sql)     {         return $this->link->query($sql);     } } 

This is then used as such:

$conexao = new Conexao("host", "username", "password", "db_name"); $result = $conexao->Query("SELECT * FROM `table` WHERE 1 ORDER BY `id` ASC;"); 

This is not only smaller, but more lightweight on the server because you aren't permanently opening and closing database connections, reducing CPU use and memory use.

Using static properties for the host etc. (keeps them in memory even after __destruct is used so you do not need to redeclare them every time):

class Conexao {     private $link;     private static $host, $username, $password, $dbName;      public function __construct($host = null, $username = null, $password = null, $dbName = null)     {         static::$host = $host ? $host : static::$host;         static::$username = $username ? $username : static::$username;         static::$password = $password ? $password : sattic::$password;         static::$dbName = $dbName : $dbName : static::$dbName;         $this->link = mysqli_init();         $this->link->real_connect(static::$host, static::$username, static::$password, static::$dbName) or die("Failed to connect");     }      public function __destruct()     {         $this->link->close();     }      public function Query($sql)     {         return $this->link->query($sql);     } }  $conexao = new Conexao("host", "username", "password", "db_name"); $result = $conexao->Query("SELECT * FROM `table` WHERE 1 ORDER BY `id` ASC;");  $conexao->__destruct(); // Destroy the class $conexao = new Conexao(); // Reinitialise it $result = $conexao->Query("SELECT * FROM `table` WHERE 1 ORDER BY `id` ASC;"); 

Using a config instance of the connection class:

config.php file:

<?php  require_once 'path/to/Conexao.php'; $conexao = new Conexao("host", "username", "password", "db_name");  ?> 

index.php file:

<?php  require_once 'config.php'; $result = $conexao->Query("SELECT * FROM `table` WHERE 1 ORDER BY `id` ASC;");  ?> 

The class now has a parent on my github!



标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!