试图像WordPress循环一样在循环时自行制作



我最近阅读了这篇文章:如何像wordpress循环一样自行制作自己的循环?到目前为止

本文中给出的答案建议一种OOP方法,而不是使用全局变量。

我对OOP方法没有运气

而不是从mysql表中显示" item_title"one_answers" item_desc"值,而是出现字母。请注意,这些字母以正确的循环格式。

我在做什么错?

非常感谢

<?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;
?>

您正在错误地做mySQL。mysqli_fetch_array获取单行数据。它不会在查询结果中检索所有行。您的查询也效率低下。如果您只想计算有多少帖子,可以做

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

但这是低效的 - 您正在强迫数据库库开始在您实际要使用的假设上获取行数据。但是,您只是将其扔掉。更好的方法是

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

稍后您将$posts对待,就像它确实包含所有查询结果一样,但是由于它仅包含一行,因此您只是迭代/获取该行的字段。

,我可以看到您只是使用

查询一行

$posts = mysqli_fetch_array($get_item_res);

您需要用所有thoses行填充一个阵列。

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

相关内容

最新更新