doutang0335 2014-05-30 11:23
浏览 65
已采纳

如何为未序列化的类别编写查询

so my function post() does the next thing:

$category = serialize($postdata['post_category']);
        $query = "
                 INSERT INTO posts(post_title, post_content, post_category)
                 VALUES ('$postdata[post_title]', '$postdata[post_content]', '$category')
                 ";   

inserts serialized data into the database, but i have a problem when calling a function to show only those posts which have same category, a function for that looks like this:

public function cat($cat){
        global $db;
        $query = "
                 SELECT * FROM posts
                 WHERE post_category LIKE '%$cat%'
                 ";
        return $db->select($query);
    }   

So my question is: is it better to insert unserialized data into database for this particular case (and how to do that) or is it better to pull serialized data and then unserialize it for showing some particular posts (same as previous, tried a couple of options and had no luck achieving the right result) ?

  • 写回答

2条回答 默认 最新

  • duanchao9559 2014-05-30 11:52
    关注

    If $postdata['post_category'] is an array, you could also insert multiple categories in the same column:

    $category = ',' . implode(',', $postdata['post_category']) . ',';
    $query = "
         INSERT INTO posts(post_title, post_content, post_category)
         VALUES ('$postdata[post_title]', '$postdata[post_content]', '$category')
         ";
    

    Mind that you always should have comma at the end and the beggining of the categories string like so: ,1,2,3,4,!

    To select the posts from a category:

    public function cat($cat){
        global $db;
        $query = "
                 SELECT * FROM posts
                 WHERE post_category LIKE ',$cat,'
                 ";
        return $db->select($query);
    }
    

    But this method will not allow you to select posts from multiple categories.

    Note: You should consider learning to use multiple tables and JOIN-ining them. One table for posts, one table for categories and one table post_to_categories, where all the categories with their specific posts are linked.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 BP神经网络控制倒立摆
  • ¥20 要这个数学建模编程的代码 并且能完整允许出来结果 完整的过程和数据的结果
  • ¥15 html5+css和javascript有人可以帮吗?图片要怎么插入代码里面啊
  • ¥30 Unity接入微信SDK 无法开启摄像头
  • ¥20 有偿 写代码 要用特定的软件anaconda 里的jvpyter 用python3写
  • ¥20 cad图纸,chx-3六轴码垛机器人
  • ¥15 移动摄像头专网需要解vlan
  • ¥20 access多表提取相同字段数据并合并
  • ¥20 基于MSP430f5529的MPU6050驱动,求出欧拉角
  • ¥20 Java-Oj-桌布的计算