我对PHP很新,我一直在环顾四周,似乎无法找到我正在寻找的具体答案.
我想创建一个SQL查询,例如:
$result = mysqli_query($connection, $command)
if (!$result) { die("Query Failed."); }
// Create my array here ... I'm thinking of maybe having to
// make a class that can hold everything I need, but I dunno
while($row = mysqli_fetch_array($result))
{
// Put the row into an array or class here...
}
mysqli_close($connection);
// return my array or class
Run Code Online (Sandbox Code Playgroud)
基本上我想获取结果的全部内容并创建一个我可以以与行类似的方式访问的数组.例如,如果我有一个名为'uid'的字段,我希望能够通过myData ['uid']获得该字段.我想因为可能有几行,可能更像myData [0] ['uid'],myData [1] ['uid']等.
任何帮助,将不胜感激.
kar*_*ikr 18
你可以做:
$rows = [];
while($row = mysqli_fetch_array($result))
{
$rows[] = $row;
}
Run Code Online (Sandbox Code Playgroud)
您可能会尝试使用mysqli_result::fetch_all()
数组:
$result = mysqli_query($connection, $command)
if (!$result) { die("Query Failed."); }
$array = $result->fetch_all();
$result->free();
mysqli_close($connection);
Run Code Online (Sandbox Code Playgroud)
注意:这仅适用于MySQLND.
对于课程,您可能会尝试使用以下内容:
$result = mysqli_query($connection, $command)
if (!$result) { die("Query Failed."); }
while($model = $result->fetch_assoc()){
// Assuming ModelClass is declared
// And have method push() to append rows.
ModelClass::push($model);
}
$result->free();
mysqli_close($connection);
Run Code Online (Sandbox Code Playgroud)
或这个:
// Base Model - abstract model class.
class ModelClass extends BaseModel {
// constructor
public function __construct(mysqli &$dbms){
// $this->dbms is MySQLi connection instance.
$this->dbms = &$dbms;
// $this->models is buffer for resultset.
$this->models = array();
}
// destructor
public function __destruct(){
unset($this->dbms, $this->models);
}
public function read(){
$result = $this->dbms->query($command);
if($this->dbms->errno){
throw new Exception($this->dbms->error, $this->dbms->errno);
}
$this->models = $result->fetch_all();
$result->free();
}
}
Run Code Online (Sandbox Code Playgroud)