gpt4 book ai didi

php - 获取数组中的sql数据

转载 作者:行者123 更新时间:2023-11-29 12:34:49 25 4
gpt4 key购买 nike

我正在尝试创建非常简单的类,我可以在其中从表中检索数据。

class dbCore{
private $username;
private $password;
private $database;
private $serverAddress;
private function createConnection(){
return mysql_connect($this->serverAddress, $this->username, $this->password);
}

public function __construct($db=array()){
$this->username = $db['username'];
$this->password = $db['password'];
$this->database = $db['database'];
$this->serverAddress = $db['serverAddress'];
}

public function checkConnection(){
$connection = $this->createConnection();
if( $connection )
mysql_close($connection);
return !!$connection;
}

public function getAll($tableName){
$data=array();
$connection = $this->createConnection();
$sql = "SELECT * FROM " . $tableName;
if ($connection){
mysql_select_db($this->database);
$result=mysql_query($sql, $connection);
while ($row = mysql_fetch_row($result)) {
array_push($data,$row);
}
return $data;
}else{
return false;
}

}
}

当我调用 $db->getAll('mytable'); 时,它会检索:

Array
(
[0] => Array
(
[0] => 1
[1] => Riga
[2] => Liepaja
[3] => 2014-11-20
[4] => 2014-11-08
[5] => 4
)

[1] => Array
(
[0] => 2
[1] => Riga
[2] => Liepaja
[3] => 2014-11-19
[4] => 2014-11-09
[5] => 3
)

)

但我希望它是 id => 1, city => Riga 等。但我不想自己写。我希望它从列名中获取并放入键值。有简单的方法吗?我可以检索所有字段名称并替换它们,但似乎效率不高。

最佳答案

为什么你还在使用mysql_?它已被弃用。

无论如何,使用mysql_fetch_assoc而不是mysql_fetch_row

关于php - 获取数组中的sql数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26952655/

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