2014-01-09 39 views
0

所以我已經連接到我的mySQL數據庫,並且能夠查看錶中我想從中提取信息的所有列。現在我需要能夠從「ds_users」中的「password」和「username」中的特定字段中讀取所有值。我想將它們存儲到一個數組中並打印出來。這裏是我到目前爲止的代碼:如何使用php從mySQL表中提取特定值?

$result = mysql_query("SHOW COLUMNS FROM ds_users"); 
if (!$result) { 
    echo 'Could not run query: ' . mysql_error(); 
    exit; 
} 
if (mysql_num_rows($result) > 0) { 
    while ($row = mysql_fetch_assoc($result)) { 
     print_r($row); 
    } 
} 

另外,有沒有辦法以JSON格式打印結果?

+2

'json_encode()':) –

+1

對不起,但我在這裏沒有看到任何問題,對PHP手冊的簡短訪問可能會導致超過10分鐘的未答覆。 –

+0

好的,很酷。我在網上看到了這個消息,但是我對所有可用的JSON編碼選項有點困惑。謝謝! –

回答

1
$result = mysql_query("SELECT username, password FROM ds_users"); 
if (!$result) { 
    echo 'Could not run query: ' . mysql_error(); 
    exit; 
} 
if (mysql_num_rows($result) > 0) { 
    while ($row = mysql_fetch_assoc($result)) { 
     $dataArray['user'] = $row->user; 
     $dataArray['password'] = $row->password; 
    } 
    print_r(json_encode($dataArray)); 
} 

在側面說明轉換成JSON格式:MySQL的功能已棄用,您應該在mysqli或PDO之間進行選擇。

+0

某處可能有語法錯誤?我完全可以得到這個工作。 –

+0

好吧,我明白了! –

+0

沒有語法錯誤,它應該工作... – gbestard

1

使用json_encode()在PHP

$arr = array(); 
if (mysql_num_rows($result) > 0) { 
    while ($row = mysql_fetch_assoc($result)) { 
     $arr[] = $row; 
    } 
} 

print_r(json_encode($arr)); 
1

要存儲在陣列

$dataArray = array(); 
    if (mysql_num_rows($result) > 0) { 
     while ($row = mysql_fetch_assoc($result)) { 
      $dataArray[] = $row; 
     } 
    } 

使用json_encode功能

$jsonString = json_encode($dataArray); 
相關問題