2016-07-27 45 views
0

我的數據庫包含表user - >字段 - >usernameuserid擷取結果從MySQL查詢PHP數組

$user = (" SELECT userid,username FROM user "); 
    while ($row = @mysql_fetch_assoc($user)) 
    { 
    $getalluser[] = $row; 
    } 

我試圖讓數組的結果是這樣的:

$users = array(
0=>array(
    "Mark", 
    "http://localhost/test/image.php?u=1", 
    "Mark" 
), 
1=>array(
    "Anandu", 
    "http://localhost/test/image.php?u=2", 
    "anandu" 
), 
    2=>array(
    "jeena", 
    "http://localhost/test/image.php?u=3", 
    "jeena" 
) 
); 

注意:

Mark,Anandu,jeena - > username AND u=1,u=2,u=3 - > userid

+1

定義網址,以便您不要重複自己:'$ URL = 'HTTP://localhost/test/image.php U =?';'。然後,在循環中:'$ getalluser [] = array($ row ['username'],$ url。$ row ['userid']);'(我沒有包含用戶兩次因爲我看不到需要它) – FirstOne

+2

請[停止使用mysql_ *函數](http://stackoverflow.com/questions/12859942/why-shouldnt-i-use-mysql-functions-in-php)。該擴展在PHP 5.5.0中被棄用,並且在PHP 7.0.0中被刪除。相反,[MySQLi](http://php.net/manual/en/book.mysqli.php)或[PDO_MySQL](http://php.net/manual/en/ref.pdo-mysql.php)應該使用擴展名。另請參見[MySQL:選擇API](http://php.net/manual/en/mysqlinfo.api.choosing.php)指南和[相關FAQ](http://php.net/manual/en/faq .databases.php#faq.databases.mysql.deprecated)以獲取更多信息。 – FirstOne

+0

@FirstOne,謝謝兄弟..我會嘗試你的代碼 –

回答

0

我安裝了PHP7,因此我無法使用您正在使用的mysql_xxx函數(它們已被棄用)。我不得不使用mysqli_xxx功能爲了測試下一個代碼:

<?php 
$cnx = mysqli_connect("localhost", "root", "pass", "databasename"); 
$data = mysqli_query($cnx, "SELECT userid,username FROM user"); 
$getalluser = array(); 
while ($row = mysqli_fetch_array($data)) 
    $getalluser[] = array($row[ "username" ], 
         "http://localhost/test/image.php?u=" . $row[ "userid" ], 
         $row[ "username" ]); 
var_dump($getalluser); 
?> 

空數組是while之前創建的。在while數組中填充數組,這些數組每個包含3個項目:用戶名作爲第一項和第三項,URL作爲第二項。第二項在末尾連接了userid

+0

現在我會嘗試,感謝兄弟 –

+0

它的工作太好了,非常感謝 –