php - OOP PHP 集成 mysqli_query

标签 php mysql oop mysqli integrate

我将编辑问题以使其更清楚,这样您就可以看到我现在得到的内容,并更容易理解问题。

<?php
$mysqli = new mysqli("localhost", "user", "password", "test");
class building
{
private $mysqli;
public $buildingid;
public $userid;
public $buildinglevel;




public function __construct($buildingid, $userid, \mysqli $mysqli)
{
    $this->buildinglevel;
    $this->mysqli = $mysqli;
}

public function getLevel()
{
    return $this->mysqli->query("SELECT ".$this->buildingid." FROM worlds WHERE city_userid=".$this->userid."");
}
}

}
?>

然后我用它来创建和使用函数:

$cityHall = new building("cityHall",$user['id'],$mysqli);
echo $cityHall->getLevel();

结果是空白,没有任何反应。

最佳答案

你应该将 mysqli 的实例注入(inject)到构建类的 __construct() 中:

$mysqli = new mysqli('用户', '密码', '本地主机', '测试');

如果($mysqli->connect_errno){ printf("连接失败: %s\n", $mysqli->connect_error);

class building
{
private $mysql;
private $buildingid;
private $userid;

// I need to have a mysqli_query here to get the info for the correct building, 
//to be able to set the "buildinglevel" for each object from the MYSQL DB, seems basic   
//but none of the things ive tried has worked.


public function __construct($buildingid, $userid, $mysqli)
{
    $this->buildinglevel;
    $this->mysqli = $mysqli;
    $this->userid = (int)$userid;
    $this->buildingid= (int)$buildingid;
}

public function getLevel()
{
    $query = $this->mysqli->query("SELECT ".$this->buildingid." FROM worlds WHERE city_userid=".$this->userid);
    $row = $query->fetch_assoc();
    if (!$query) {
        return $this->mysqli->error;
    }
    if ($query->num_rows == 0) {
        return 'no database records found';
    }

    return $row;
}

}

$Bulding = new building("cityHall", $user['id'], $mysqli);
$level = $Bulding->getLevel();
var_dump($level);

关于php - OOP PHP 集成 mysqli_query,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19293957/

相关文章:

mysql - 为什么我的 rand() 代码在 mysql 中不起作用?

php - 原则 2 让我质疑集合的目标,一般来说,我可以在集合中使用哪些方法?

java - 良好的面向对象设计

php - 更新 laravel mysql 数据库中的行

php - 声云声波

php - 找不到 Laravel 5.2 类,但类有命名空间

php - Sublime Text 3 错误 : Warning. 需要 PHP 5.6 或更新版本。请升级您的本地 PHP 安装

php - 防止多个 mysql 数据/表单提交并更新现有条目?

mysql - MySQL 中 UNIX_TIMESTAMP 输出 NULL?

php - Class::getInstance 的起源/解释?