2012-09-04 43 views
5

過去兩天左右,我一直在將我的函數轉換爲mysqli。我遇到了一個問題。我有一個函數返回一個數組中包含一行的數組。不過,我希望數組包含多行而不是一行。另外,我將如何能夠回顯個別帖子。這是我失敗的嘗試,只顯示數組中的一行。用MySqli和數組返回多行

$mysqli = new mysqli("localhost", "user", "password", "database"); 

function display_posts ($mysqli, $user_id) { 

    $fields = "`primary_id`, `poster_id`, `profile_user_id`, `post`"; 

    $user_id = (int)$user_id; 

    $query = "SELECT DISTINCT $fields FROM `posts` WHERE `profile_user_id` = $user_id 
    LIMIT 4";      

    if ($result = $mysqli->query($query)) { 

    $row = $result->fetch_assoc(); 

    return $row; 

    $result->free(); 

    $stmt->close(); 

}} 

這裏我試圖顯示數據。

$user_id = 1; 

$posts = display_posts($mysqli, $user_id); 

//Not sure what to do with $posts. A While loop perhaps to display each post? 

回答

11

你必須使用一個循環,讓他們一下子:

<?php 
function resultToArray($result) { 
    $rows = array(); 
    while($row = $result->fetch_assoc()) { 
     $rows[] = $row; 
    } 
    return $rows; 
} 

// Usage 
$query = 'SELECT DISTINCT $fields FROM `posts` WHERE `profile_user_id` = $user_id LIMIT 4'; 
$result = $mysqli->query($query); 
$rows = resultToArray($result); 
var_dump($rows); // Array of rows 
$result->free(); 
+0

雖然我希望能得到一個答案如何ec ho出每個個人的價值,然後自己想出來。儘管如此,感謝您的幫助。我決定取出函數'resultToArray'並將其附加到我原來的函數中。 – jason328

5

爲什麼不直接使用這樣的:

$result = mysqli_fetch_all($mysqli->query($query), MYSQLI_ASSOC); 
+1

這將是一個更好的答案,如果你解釋爲什麼它的工作 –

+1

@ KateGregory實際上沒有什麼可以解釋的。除了這個函數僅在5.3以後纔可用,並且只能在mysqlnd下使用。 –

+0

沒什麼好解釋的。而不是做一段時間週期,使用可用的mysqli方法來獲取整個結果集。也避免爲它聲明一個額外的功能。是的,它大於5.3。但據我所知,mysqli也是5.3以上 –

1

我來晚了,但我相信這是你想實現的:

$mysqli = new mysqli("localhost", "user", "password", "database"); 
$fields = "`primary_id`, `poster_id`, `profile_user_id`, `post`"; 

function display_posts() { 

    global $mysqli; 
    global $fields; 

    $query = "SELECT DISTINCT $fields FROM `posts` WHERE `profile_user_id` = $user_id LIMIT 4"; 

    $posts = $mysqli -> query($query) or die('Error: '.$mysqli -> error); 

    if ($posts -> num_rows > 0) { 

     while ($row = $posts -> fetch_assoc()) { 

     $value = $row['/*The table column here (You can repeat this line with a different variable e.g. $value 2, $value 3 etc and matching them with the respective table column)*/']; 

     echo $value./*Concatenate the other variables ($value 1 etc) here*/'<br />'; 

     } 

    }else { 

     echo 'No records found.'; 

    } 

} 

//Call the function 
display_posts();