尝试检索结果时,使用PHP类连接到数据库无法正常工作 [英] Connect to DB with PHP Class isn't working when try to retrieve results

查看:97
本文介绍了尝试检索结果时,使用PHP类连接到数据库无法正常工作的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

早上好.

我正在尝试制作一个数据库类来连接数据库并从数据库中检索结果.因此,我认为与全班同学一起,一切都很好.但是结果不会出现.

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.

这是我的数据库课程:

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

推荐答案

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

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

然后按如下方式使用:

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

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

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.

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

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文件:

config.php file:

<?php

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

?>

index.php文件:

index.php file:

<?php

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

?>

该类现在在我的github 上有一个父级!

The class now has a parent on my github!

这篇关于尝试检索结果时,使用PHP类连接到数据库无法正常工作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆