2014-11-01 93 views
0

我想選擇表格的最後4行,然後將它們放入一個JSON數組中,每個數據附加一個數字,以便稍後可以訪問它們,我想一個循環,但不知道如何與計數器次數爲如何從表中將多行數據放入JSON數組

是可以獲得最後四排部分

SELECT title FROM questions ORDER BY id DESC LIMIT 4 

和數組像1: data one, 2: data two...

回答

1

阿隆,你可以使用下面的代碼: -

$mysqli = new mysqli("localhost", "dbusername", "dbpassword", "sakila"); 
$x = 1; 
$return_arr = array(); 
$result = $mysqli->query("SELECT title from questions ORDER By id DESC LIMIT 4"); 
while($obj = $result->fetch_object()) { 
    $row_array[$x] = $obj->title; 
    $x++; 
} 
$result->close(); 
array_push($return_arr,$row_array); 
echo json_encode($return_arr);`//result [{"1":"title1","2":"title2","3":"title3}] 

這裏在循環中,我將值存儲在一個數組($ row_array)。這裏$ x將包含數字(鍵)。然後將完整的結果推入一個新的數組中,並將結果轉換爲一個json數組。

0
  1. Buil d數據庫連接字符串,例如使用MySQLI。
  2. 查詢數據庫中的行。
  3. 使用fetchAll()函數抓取所有行,傳遞MYSQLI_NUM常量來告訴它返回一個數字索引數組,而不是關聯返回的json_encode和相關聯的

下面的代碼是什麼樣子:

$mysqli = new mysqli('localhost', 'user', 'pass', 'database'); 
$stmt = $mysqli->query('SELECT title FROM questions ORDER BY id DESC LIMIT 4'); 
echo json_encode($stmt->fetchAll(MYSQLI_NUM)); 
0

檢查下面的代碼使用PDO,也可以更改爲mysqli的

$dbh = new PDO('mysql:host=localhost:33060;dbname=demo', 'root', ''); 

$sth = $dbh->prepare("SELECT title FROM questions ORDER BY id DESC LIMIT 4"); 
$sth->execute(); 
$result = $sth->fetchAll(PDO::FETCH_COLUMN); 

//Key should be string, otherwise, we can not encode as json 
foreach($result as $key => $value) { 
    $newkey = sprintf('%s',$key); 
    $newArray["k$newkey"] = $value; 
} 

echo json_encode($newArray); //result: {"k0":"title 4","k1":"title 3","k2":"title 2","k3":"title 1"} 
相關問題