我最近讀了這篇文章: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;
?>