2014-04-03 84 views
-1

我有此數組:PHP使MySQL查詢顯示爲陣列

$urls = array(
    0 => array('url' => 'phpclasses.org', 'keyword' => 'phpclass'), 
    1 => array('url' => 'phpclasses.org', 'keyword' => 'php'), 
    2 => array('url' => 'php.com', 'keyword' => 'php') 
); 

我的問題是,我想,以取代以上我是從數據庫中獲取數據的數據。

我有一個具有以下字段的表:

id(auto), url and keyword. 

然後我連接到數據庫:

$con=mysqli_connect("localhost","root","","my_db"); 
// Check connection 
if (mysqli_connect_errno()) 
    { 
    echo "Failed to connect to MySQL: " . mysqli_connect_error(); 
    } 

$result = mysqli_query($con,"SELECT * FROM my_table"); 

我的問題是我怎麼能創建一個mysqli的查詢,將得到的數據上面的數組的格式?

+0

如何從MySQL中獲取數據? – Ibu

+0

它看起來像列名稱的索引,因此您只需遍歷結果集並將每行從數據庫添加到數組。如果列名不符合你想要的索引,那麼你可以使用'AS'來爲你的查詢結果重新命名列名。 – Jasper

回答

0

嘗試這樣

<?php 
mysql_connect("localhost", "username", "password"); 
mysql_select_db("DATABASE"); 

$urls = array(); 

$query = mysql_query("SELECT * FROM YOUR_TABLE"); 

while($row = mysql_fetch_array($query)) { 
$urls[] = array('url' => $row['url'], 'keyword' => $row['keyword']); 
} 

var_dump($urls); 
?> 

與您的代碼:

<?php 
$con=mysqli_connect("localhost","root","","my_db"); 
if (mysqli_connect_errno()) 
    { 
    echo "Failed to connect to MySQL: " . mysqli_connect_error(); 
    } 
$result = mysqli_query($con,"SELECT * FROM my_table"); 

$urls = array(); 

while($row = mysql_fetch_array($result)) { 
$urls[] = array('url' => $row['from_id'], 'keyword' => $row['to_id']); 
} 

var_dump($urls); 
?> 

投票了,如果答案幫助你。

+0

如果其中一行從數據庫中刪除,並且您嘗試通過數組的索引達到id,該怎麼辦?這個例子會不一致。 –

+0

您只定義了帶ID的數組的數量,他沒有告訴我們定義它;)並且如果行從數據庫中刪除,他也會從數組中刪除! – Mombay

+0

是的,讓我們忽略所有事情,只是不去幫助別人,因爲「他沒有告訴我們去定義它」已經定義了什麼。 –

1

下面這段代碼複製您的數組,數組的索引是數據庫中的id字段,其​​他值位於數組內。

<?php 
$con = mysqli_connect("localhost","root","","my_db"); 
// Check connection 
if (mysqli_connect_errno()) { 
    echo "Failed to connect to MySQL: " . mysqli_connect_error(); 
} 

$result = mysqli_query($con, "SELECT * FROM my_table"); 

$urls = array(); 

while ($row = mysqli_fetch_array($result)) { 
    $urls[$row['id']] = array('url' => $row['url'], 'keyword' => $row['keyword']); 
} 

var_dump($urls); 
?>