0
我試圖做出非常簡單的類,我可以從表中檢索數據。檢索數組中的sql數據
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
等,但我不想把它寫自己。我希望它能夠從列名中提取關鍵值。有沒有簡單的方法來做到這一點?我可以檢索所有字段名稱並替換它們,但似乎效率不高。
這是第一次我在網上找到。我應該使用什麼? – Cirvis
使用mysqli http://php.net/manual/en/book.mysqli.php或PDO http://php.net/manual/en/book.pdo.php – rjdown