显示数据库中的类别

时间:2017-10-16 04:45:02

标签: php html

我正在尝试在HTML表格上显示每个帖子的类别,并且没有给出任何错误。

嗯,查询很好。我没有找到任何拼写错误的变量。

I get the post status in category side

<?php
$query = "SELECT * FROM  posts";
$se_posts = mysqli_query($connection,$query);
while ($row = mysqli_fetch_assoc($se_posts)) {
    $post_id = $row['post_id']; 
    $post_author = $row['post_author']; 
    $post_title = $row['post_title']; 
    $post_category_id = $row['post_category_id']; 
    $post_status = $row['post_status']; 
    $post_image = $row['post_image']; 
    $post_tags = $row['post_tags']; 
    $post_comment_count = $row['post_comment_count']; 
    $post_date = $row['post_date']; 

    echo "<tr>";
    echo "<td>{$post_id}</td>";
    echo "<td>{$post_author}</td>";
    echo "<td>{$post_title}</td>";

    // show post category
    $query = "SELECT * FROM categories WHERE cat_id Like $post_category_id";
    $query_update_cat = mysqli_query($connection, $query);

    while ($row = mysqli_fetch_assoc($query_update_cat)) {
        $cat_id = $row['cat_id'];  
        $cat_title = $row['cat_title'];

        echo "<td>{$cat_title}</td>";
    }

    echo "<td>{$post_status}</td>";
    echo "<td><img class='img-responsive' width='100'src='../images/{$post_image}'></td>";
    echo "<td>{$post_tags}</td>";
    echo "<td>{$post_comment_count}</td>";
    echo "<td>{$post_date}</td>";
    echo "<td><a href='post.php?delete={$post_id}'>delete</a></td>";
    echo "<td><a href='post.php?source=edit_post&p_id={$post_id}'>Edit</a></td>";

    echo "</tr>";
}  
?>

1 个答案:

答案 0 :(得分:0)

有一个问题是您在每个帖子(或文章)上发出请求。 这是错误的,你应该尽可能多地减少请求的数量。另外,你正在使用LIKE !!你应该使用相同的&#39; =&#39;。

您的查询:

在这个类别循环中你应该在循环之前定义$ cat_title,然后在循环中设置它,并在循环之外打印它:

$cat_title = "";
while($row = mysqli_fetch_assoc($query_update_cat)){
    $cat_id = $row['cat_id'];  
    $cat_title = $row['cat_title'];
}
echo "<td>{$cat_title}</td>";

使用JOIN尝试此查询:

<?php
$query = "SELECT * FROM  posts JOIN categories ON (posts.post_category_id = categories.cat_id)";

$se_posts= mysqli_query($connection,$query);
?>
<table>
<tr>
    <td>post id</td>
    <td>post author</td>
    <td>post title</td>
    <td>category</td>
    <td>post status</td>
    <td>image</td>
    <td>tags</td>
    <td>comment count</td>
    <td>date</td>
    <td>action</td>
</tr>
<?php
while($row = mysqli_fetch_assoc($se_posts)) {
    echo "<tr>";
    echo "<td>{$row['post_id']}</td>";
    echo "<td>{$row['post_author']}</td>";
    echo "<td>{$row['post_title']}</td>";
    echo "<td>{$row['cat_title']}</td>";
    echo "<td>{$row['post_status']}</td>";
    echo "<td><img class='img-responsive' width='100'src=\"../images/{$row['post_image']}\"></td>";
    echo "<td>{$row['post_tags']}</td>";
    echo "<td>{$row['post_comment_count}</td>";
    echo "<td>{$row['post_date']}</td>";
    echo "<td><a href=\"post.php?delete={$row['post_id']}\">delete</a></td>";
    echo "<td><a href=\"post.php?source=edit_post&p_id={$row['post_id']}\">Edit</a></td>";
echo "</tr>";
}
?>
</table>