2014-09-12 30 views
0

我有一個函數用於從數據庫中選擇要顯示在表中的數據。該功能正在生成一個無限循環。我該如何解決這個問題?Mysql select查詢/ PHP函數正在生成一個無限循環

我的代碼如下:

function view() 
{ 
    $db = new mysqli("localhost", "root", "", "blog"); 
    $sql = 'SELECT * FROM news'; 
    $result = $db->query($sql) or die($mysqli->error); 
    return $result->fetch_assoc(); 
} 
?> 
<table> 
    <tr> 
    <th scope="col">Title</th> 
    <th scope="col">Slug</th> 
    <th scope="col">Text</th> 
    </tr> 
    <?php while($row = view()) { ?> 
    <tr> 
    <td><?php echo $row['title']; ?></td> 
    <td><?php echo $row['slug']; ?></td> 
    <td><?php echo $row['text']; ?></td> 
    </tr> 
    <?php } ?> 
</table> 

感謝。

回答

2

嘗試此:

function view() 
{ 
    $db = new mysqli("localhost", "root", "", "blog"); 
    $sql = 'SELECT * FROM news'; 
    $result = $db->query($sql) or die($mysqli->error); 

    $results=array(); 
    while($row=$result->fetch_assoc()) 
     $results[] = $row; 

    return $results; 
} 
?> 
<table> 
    <tr> 
    <th scope="col">Title</th> 
    <th scope="col">Slug</th> 
    <th scope="col">Text</th> 
    </tr> 
    <?php $results = view(); 
     foreach($results as $result_index=>$result_values) { ?> 
    <tr> 
    <td><?php echo $result_values['title']; ?></td> 
    <td><?php echo $result_values['slug']; ?></td> 
    <td><?php echo $result_values['text']; ?></td> 
    </tr> 
    <?php } ?> 
</table> 
2

你的函數在你每次調用它時重新執行查詢。

讓你的函數返回$ result變量,然後讓你的while循環是這樣的:

<?php $result = view(); while($row = $result->fetch_assoc()) { ?> 
    <tr> 
    <td><?php echo $row['title']; ?></td> 
    <td><?php echo $row['slug']; ?></td> 
    <td><?php echo $row['text']; ?></td> 
    </tr> 
<?php } ?> 

編輯:你的觀點()函數應該是這樣的:

function view() 
{ 
    $db = new mysqli("localhost", "root", "", "blog"); 
    $sql = 'SELECT * FROM news'; 
    return $db->query($sql) or die($mysqli->error); 
} 
+0

功能視圖() { \t $分貝= new mysqli(「localhost」,「root」,「」,「blog」); \t $ sql ='SELECT * FROM news'; \t返回$ result = $ db-> query($ sql)或die($ mysqli-> error); }但是這是我得到的錯誤致命錯誤:調用第25行中C:\ wamp \ www \ Custom-Menu \ array-from-function.php中的非對象上的成員函數fetch_assoc() – Terungwa 2014-09-12 21:48:38