PHP,类别,SELECT FROM INNER JOIN WHERE

时间:2014-01-23 21:19:44

标签: php mysql select where categories

嗨我试图让这个特定的代码适用于类别页面。不知道如何安排。

        $cat = $_GET['cat'];
}
$record_count = $db->query("SELECT * FROM posts WHERE category_id='$cat'");
$per_page = 3;
$pages = ceil($record_count->num_rows/$per_page);

echo $cat;

if (isset($_GET['p']) && is_numeric($_GET['p'])){
    $page = $_GET['p'];
}else{
    $page = 1;
}
if($page<=0)
    $start=0;
    else
    $start = $page * $per_page - $per_page;
$prev = $page - 1;
$next = $page + 1;
$query = $db->prepare("SELECT post_id, title, date, image, LEFT(body, 150) AS  body, category FROM posts WHERE posts.category_id=$cat INNER JOIN categories ON categories.category_id=posts.category_id order by post_id desc limit $start, $per_page");
$query->execute();
$query->bind_result($post_id, $title, $date, $image, $body, $category );

这包括pagnation,特别关注这一行。但要分离所需的category_id似乎比预期的更难(至少对我而言)

$query = $db->prepare("SELECT post_id, title, date, image, LEFT(body, 150) AS  body, category FROM posts WHERE posts.category_id=$cat INNER JOIN categories ON categories.category_id=posts.category_id order by post_id desc limit $start, $per_page");

使用两个mysql表

帖子:post_id标题日期图片正文链接linkname category_id

类别:category category_id

1 个答案:

答案 0 :(得分:2)

您的查询部分不按顺序(具体而言,WHERE的位置)并且您没有正确地执行预准备语句。请注意,您在每个变量的位置放置一个问号,然后使用bind_param按顺序填写问号。第一部分"iii"表示有三个整数。

$query = $db->prepare("SELECT post_id, title, date, image, LEFT(body, 150) AS  body, category 
    FROM posts 
    INNER JOIN categories ON categories.category_id=posts.category_id 
    WHERE posts.category_id=? 
    order by post_id desc 
    limit ?, ?");
$query->bind_param("iii", $cat, $start, $per_page);
$query->execute();