我需要这样的东西。
$mysqli = new mysqli($bd_host, $bd_user, $bd_password);
class webFile {
function __construct($querystr){
if ($result = $this->$mysqli->query($querystr)) {
while( $row = $result->fetch_assoc() ){ echo $row['name']; }
$result->close();
}}}
$object = new webFile($querystr);
我尝试了不同的变体,但有些想法不起作用。
我对mysqli->query
而不是mysqli_query(a,b);
UPD 1.你的解决方案不起作用。 谢谢,工作正常,问题还在于DB。
答案 0 :(得分:1)
您需要使用global
让PHP查看全局范围并查看您的$mysqli
变量,因为这是一个全局变量,您无法使用$this
:
$mysqli = new mysqli($bd_host, $bd_user, $bd_password);
class webFile {
function __construct($querystr){
global $mysqli;
if ($result = $mysqli->query($querystr)) {
while( $row = $result->fetch_assoc() ){ echo $row['name']; }
$result->close();
}}}
$object = new webFile($querystr);
您也可以将MySQLi
对象传递给构造函数并拥有属性:
$mysqli = new mysqli($bd_host, $bd_user, $bd_password);
class webFile {
function __construct($querystr, $conn){
$this->mysqli = $conn;
if ($result = $this->mysqli->query($querystr)) {
while( $row = $result->fetch_assoc() ){ echo $row['name']; }
$result->close();
}}
private $mysqli;
}
$object = new webFile($querystr, $mysqli);
答案 1 :(得分:1)
你可以这样做,将连接注入到类构造函数中。
<?php
$dbhost = 'localhost';
$dbuser = 'root';
$dbpwd = 'xxx';
$dbname = 'xxx';
$oConn=new mysqli($dbhost, $dbuser, $dbpwd, $dbname);
class webFile{
private $conn;
public function __construct( $conn=object, $sql=false, $field=false ){
if( $conn && $sql && $field ){
$this->conn=$conn;
$res=$this->conn->query( $sql );
if( $res ){
while( $rs=$res->fetch_object() ) echo $rs->$field;
}
}
}
}
$obj=new webFile( $oConn, 'select * from users', 'user' );
?>