gpt4 book ai didi

php - OOP PHP 集成 mysqli_query

转载 作者:太空宇宙 更新时间:2023-11-03 12:22:24 25 4
gpt4 key购买 nike

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

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

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com