用PHP类连接数据库是';尝试检索结果时无法工作


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

早上好。

我正在尝试创建一个DB类来连接我的DB并从中检索结果。所以,我认为有课就是一切都好。但是,结果不会出现。

这是我的DB类:

<?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;
}
}
?>

这里是我试图检索结果的地方:

<?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>';
}
 ?>

我尝试了一些修改,但没有什么变化。每次它仍然不起作用。怎么了?

由于Comando::Executar不是静态的,而是声明为public function...,因此必须执行以下操作:

$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>';
}

或者将方法声明为静态,即:

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

然后您可以使用双冒号(::)语法:

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

我建议不要每次运行查询时都调用open和close,而应该调用这样的类:

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);
    }
}

然后这样使用:

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

这不仅更小,而且在服务器上更轻,因为您不会永久打开和关闭数据库连接,从而减少CPU使用和内存使用。

为主机等使用静态属性(即使在使用__destruct之后也将它们保存在内存中,因此不需要每次都重新声明它们):

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;");

使用连接类的配置实例:

config.php文件:

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

index.php文件:

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

该类现在在我的github上有一个家长!