我已经构建了自己的CMS,并使用数据库 wp_posts 和 wp_postmeta 来填充我的网站。
当我使用SQL时,它会将所有数据从 post_content 字段中拉出来,这是一种非常奇怪的情况。有人可以查看我的查询,以确保它没问题吗?
我正在使用自己的CMS,而不是使用WordPress。
<?php
$query = "SELECT * FROM wp_posts,wp_postmeta WHERE wp_posts.ID = wp_postmeta.post_id AND
wp_postmeta.meta_key = '_wp_attached_file' ORDER BY wp_posts.post_date DESC LIMIT 0, 25";
$result = mysqli_query($connection, $query) or die(mysqli_error($connection));
while($row = mysqli_fetch_array($result)) {
$ID = $row['ID'];
$post_title = $row['post_title'];
$post_date = $row['post_date'];
$post_excerpt = $row['post_excerpt'];
$post_content = $row['post_content'];
$_wp_attached_file = $row['meta_value'];
?>
<!-- First Blog Post -->
<div class="panel panel-primary">
<div class="panel-heading">
<h3><a href="post.php?p_id=<?php echo $ID; ?>"><font color="white"><?php echo $post_title; ?></font></a></h3>
<p><span class="glyphicon glyphicon-time"></span> <?php echo humanTiming( strtotime($post_date) ); ?>
</p>
</div>
<div class="panel-body">
<img class="col-md-4" align="left" width="148" src="images/<?php echo $_wp_attached_file; ?>" alt="">
<p><?php echo $post_content; ?></p>
</div>
<p align="right"><a class="btn btn-primary" href="post.php?p_id=<?php echo $ID; ?>">Read More <span class="glyphicon glyphicon-chevron-right"> </span></a></p>
</div>
<?php
}
?>
答案 0 :(得分:2)
这个答案比建议还要多。这是您的查询:
SELECT *
FROM wp_posts, wp_postmeta
WHERE wp_posts.ID = wp_postmeta.post_id AND
wp_postmeta.meta_key = '_wp_attached_file'
ORDER BY wp_posts.post_date DESC
LIMIT 0, 25;
这是您的查询应该是这样的:
SELECT p.id, p.post_title, p.post_date, p.post_excerpt, p.post_content,
pm.meta_value as wp_attached_file
FROM wp_posts p JOIN
wp_postmeta pm
ON p.ID = pm.post_id
WHERE pm.meta_key = ?
ORDER BY p.post_date DESC
LIMIT 0, 25;
我认为您问题的解决方法是标题中列的列表。这避免了命名冲突。
其他变化:
JOIN
语法。SELECT
。如果您想学习如何编写PHP和MySQL代码,您也可以学习如何正确地编写代码。