我试图制作一个非常简单的类,我可以从表中检索数据。
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
等等。但我不想自己写。我希望它从列名中取出并放入键值。有简单的方法吗?我可以检索所有字段名称并替换它们,但它似乎效率不高。
答案 0 :(得分:1)
为什么还在使用mysql_?它被弃用了。
无论如何,请使用mysql_fetch_assoc
代替mysql_fetch_row