douci4026 2018-05-22 18:43
浏览 19

如何在数据库中分解值并在选择查询中使用它?

So, i have a checkbox in my blog for input category where the category value can be multiple. I insert them into database using implode function. Now i want my blog filter by categories if i use the below query it only gets where the category id is single. How can i fetch data where category id has multiple value. And it should be visible in every category it was checked.

public function getPublishedBlogInfoByCategory($id){
    $sql = "SELECT * FROM blogs WHERE category_id = '$id' ORDER BY id DESC";
    if(mysqli_query(Database::dbConnection(), $sql)){
        $queryResult = mysqli_query(Database::dbConnection(), $sql);
        return $queryResult;
    }else{
        die('Query problem'.mysqli_error(Database::dbConnection()));
    }
}

Here's i'm calling that function

<?php
require_once 'vendor/autoload.php';
$blog = new App\classes\Blog;
$app = new App\classes\Application;

$queryResultCategory = $blog->getAllPublishedCategory();

$id = $_GET['id'];
$queryResult = $app->getPublishedBlogInfoByCategory($id);
$queryResultCategoryName = $app->getBlogCategoryName($id);
$categoryName = mysqli_fetch_assoc($queryResultCategoryName);

$queryResultEvent = $app->getLimitedPublishedEvent();

?>

  • 写回答

1条回答 默认 最新

  • duandingcu7010 2018-05-22 18:52
    关注

    I agree with aynber that a pivot table would probably fit your needs better than a string column with multiple category ids concatenated together. However, to answer your question, rather than

    = '$id'
    

    which only matches if the entirety of the field matches the entirety of $id, you probably just need to use

    LIKE '%$id%'
    

    which treats the % as wildcards to match any number of characters before or after the $id

    EDIT:

    CREATE TABLE `blog_category_pivot` (
        `blog_id` INT(11) UNSIGNED NOT NULL,
        `category_id` INT(11) UNSIGNED NOT NULL,
        PRIMARY KEY (`blog_id`, `category_id`),
        CONSTRAINT `blog_fk` FOREIGN KEY (`blog_id`) REFERENCES `blogs` (`id`),
        CONSTRAINT `category_fk` FOREIGN KEY (`category_id`) REFERENCES `categories` (`id`)
    );
    

    Then to use the data you can just do a select from blogs and join the blog_category_pivot table to check if it has a given category. If you want to list the categories of a blog you already have an id for you can do a select name from categories joining the blog_category_pivot table on blog_id = $blog_id and category_id = categories.id

    评论

报告相同问题?

悬赏问题

  • ¥20 基于MSP430f5529的MPU6050驱动,求出欧拉角
  • ¥20 Java-Oj-桌布的计算
  • ¥15 powerbuilder中的datawindow数据整合到新的DataWindow
  • ¥20 有人知道这种图怎么画吗?
  • ¥15 pyqt6如何引用qrc文件加载里面的的资源
  • ¥15 安卓JNI项目使用lua上的问题
  • ¥20 RL+GNN解决人员排班问题时梯度消失
  • ¥60 要数控稳压电源测试数据
  • ¥15 能帮我写下这个编程吗
  • ¥15 ikuai客户端l2tp协议链接报终止15信号和无法将p.p.p6转换为我的l2tp线路