2012-10-29 117 views
0

我最近讀了這篇文章:How to make my own while Loop just like Wordpress Loop?我試圖讓自己沒有任何成功的循環到目前爲止。試圖讓我自己的while循環就像Wordpress循環

本文給出的答案建議使用OOP方法,而不是使用全局變量。

我用OOP方法沒有運氣,但全局變量方法低於幾乎可行。

不是從MySQL表中顯示'item_title'和'item_desc'值,而是顯示字母。請注意,這些字母的格式是正確的while循環。

我在做什麼錯?

非常感謝

<?php 
//CONNECT TO DATABASE 
$mysqli = mysqli_connect("localhost", "username", "password", "testDB"); 

//VALIDATE ITEMS FROM STORE_ITEMS TABLE 
$get_item_sql = "SELECT * FROM store_items"; 
$get_item_res = mysqli_query($mysqli, $get_item_sql) or die(mysqli_error($mysqli)); 

//DEFINE VARIABLES 
$posts = mysqli_fetch_array($get_item_res); 
$post = null; 
$post_count = 0; 
$post_index = 0; 

//HAVE_POST FUNCTION 
function have_post() { 
global $posts, $post_count, $post_index; 

if ($posts && ($post_index <= $post_count)){ 
    $post_count = count($posts); 
    return true; 
} 
else { 
    $post_count = 0; 
    return false; 
} 
} 

//THE_POST FUNCTION 
function the_post() { 
global $posts, $post, $post_count, $post_index; 

// make sure all the posts haven't already been looped through 
if ($post_index > $post_count) { 
    return false; 
} 

// retrieve the post data for the current index 
$post = $posts[$post_index+1]; 

// increment the index for the next time this method is called 
$post_index++; 
return $post; 

} 

//THE_TITLE FUNCTION 
function the_title() { 
global $post; 
return $post['item_title']; 
} 

//THE_CONTENT FUNCTION 
function the_content() { 
global $post; 
return $post['item_desc']; 
} 

//OUTPUT 
if(have_post()) : while(have_post()) : the_post(); 
echo '<h2>'.the_title().'</h2>'; 
echo '<p>'.the_content().'</p>'; 
endwhile; endif; 

?> 

回答

0

,我可以看到你只是使用

$posts = mysqli_fetch_array($get_item_res);

查詢一排,你需要填寫一個陣列放入系統都行,這樣一來。

$posts = array(); 
while ($row = mysqli_fetch_array($get_item_res)){ 
    $posts[] = $row; 
} 
1

你做MySQL的錯誤。 mysqli_fetch_array獲取單個數據行。它不檢索查詢結果中的所有行。你的查詢也是低效的。如果你想只是多少職位有一個數,你可以做

$result = mysqli_query("SELECT * FROM ..."); 
$rows = mysqli_num_rows($result); 

但這是低效率的 - 你強迫DB庫來啓動你實際上是將要使用的假設取行數據它。但你只是把它扔掉。更好的方式是

$result = mysqli_query("SELECT count(*) AS cnt FROM ...") or die(mysqli_error()); 
$row = mysqli_fetch_assoc($result); 
$rows = $row['cnt']; 

後來你那麼對待$posts,如果它沒有包含所有的查詢結果,但由於它僅包含一個單排,你只是遍歷/獲取一個領域行。