我不能让我的mysqli查询同时工作。如果我在html中注释掉一个函数,那么另一个函数将正确执行,反之亦然。

function all_posts() {
    require_once 'database.inc.php';
    $mysqli = mysqli_connect($host, $username, $password, $database);
    $query = mysqli_query($mysqli, "SELECT variable_name, post_name, post_date, post_display FROM blog_posts ORDER BY id DESC LIMIT 5");

    if (!$query)
        echo mysqli_error();

    while ($results = mysqli_fetch_assoc($query)) {

        $post_name = $results['post_name'];
        $post_date = $results['post_date'];
        $post_display = $results['post_display'];
        $variable_name = $results['variable_name'];

        echo "<a href='posts.php?post={$variable_name}'>";
        echo "<div class='entry'>";
        echo "<div class='entry_header'>";
        echo "<h2>{$post_name}</h2>";
        echo "<h3>{$post_date}</h3>";
        echo "</div>";
        echo "<p>{$post_display}</p>";
        echo "</div>";
        echo "</a>";
    }

    mysqli_free_result();
}

function all_sidebar_posts() {

    require_once 'database.inc.php';
    $mysqli = mysqli_connect($host, $username, $password, $database);
    $query = mysqli_query($mysqli, "SELECT variable_name, post_name FROM blog_posts ORDER BY id DESC LIMIT 5");

    while ($results = mysqli_fetch_assoc($query)) {

        $post_name = $results['post_name'];
        $variable_name = $results['variable_name'];
        echo "<li><a href='posts.php?post=$variable_name'>$post_name</a></li>";
    }

    mysqli_free_result();
}

这是我要输出到的HTML。
<ul>
    <?php all_sidebar_posts(); ?>
</ul>
</div>
<div class="content_container">
    <?php all_posts(); ?>
</div>

我试过使用mysqli_data_seek();但没有运气。也许我没用对吧?我浏览了许多问题,发现了类似的问题,但我都试过了,但都没有用。我是编程新手,所以我可能忽略了一些基本的东西。谢谢大家的帮助!

最佳答案

你做错了。
不要将数据操作代码与表示代码混合使用。
首先创建一个函数来获取帖子:

function get_posts() {
    global $mysqli;
    $sql = "SELECT variable_name, post_name, post_date, post_display
            FROM blog_posts ORDER BY id DESC LIMIT 5"
    $result = mysqli_query($mysqli, $sql);
    if (!$result) trigger_error(mysqli_error()."[$sql]");
    $date = array();
    while ($row = mysqli_fetch_assoc($result)) {
        $data[] = $row;
    }
}

这样说吧
require_once 'database.inc.php';
$mysqli = mysqli_connect($host, $username, $password, $database);
$data = get_posts();

然后使用这个数组显示

关于php - Mysqli查询两次无效,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/14657385/

10-11 05:02