简体   繁体   中英

MySql get list of pages by user_id or if user_id is not defined get all pages

I would like to get a list of pages from my MySQL table. But I want to get a list of pages added by all users if the $user_id value is NULL and if the $user_id value is defined I need to get a list of pages added by that particular user. I feel like there may be a simple solution for this, but I have tried to find a solution for this kind of situation for a long time and I failed with approaches such as "WHERE user_id is NOT NULL OR user_id = $user_id". How do I need to modify the below code to obtain expected results?

public function getPagesList($user_id = NULL){

  $this->db->query ('
    SELECT `page_id`, `page_name`
    FROM `pages`
    WHERE `user_id` = :user_id

');

$this->db->bind(':user_id', $user_id);

return $this->db->resultSet();
}

you can use a wildcard with LIKE

as Liam Sorsby pointed correctly all Pages could be a lot of pages, so you should be thinking about pagonation or Limiting the number of rows

public function getPagesList($user_id = NULL){
   $uid = is_null($user_id) ?  '%' : $user_id;
  $this->db->query ('
    SELECT `page_id`, `page_name`
    FROM `pages`
    WHERE `user_id` LIKE :user_id

');

$this->db->bind(':user_id', $uid);

return $this->db->resultSet();
}

This works like so

create table numericstring ( pk INT auto_INCREMENT PRIMARY KEY, id INT );
 insert into numericstring (id) values ( 20001 ),( 20002 ),( 30001 ),( 30002 ),( 30003 ),( 30004 ),( 37 ),( 937 ),( 21 ),( 3 ),( 222222 ),( 3333 );
 select * from numericstring WHERE id LIKE '3'
 pk |  id -: |  -: 10 |  3 
 select * from numericstring WHERE id LIKE 3
 pk |  id -: |  -: 10 |  3 
 select * from numericstring WHERE id LIKE '%'
 pk |  id -: |  -----: 1 |  20001 2 |  20002 3 |  30001 4 |  30002 5 |  30003 6 |  30004 7 |  37 8 |  937 9 |  21 10 |  3 11 |  222222 12 |  3333 

db<>fiddle here

I want to get a list of pages added by all users if the $user_id value is NULL and if the $user_id value is defined I need to get a list of pages added by that particular user.

This would translate as:

WHERE :user_id is NULL OR user_id = :user_id

When the parameter is null , this returns all rows; when the parameter is set, it is used for filtering column user_id .

You can shorten the expression a little with coalesce() , but it might be less efficient:

WHERE COALESCE(:user_id, user_id) = user_id

Note that, as commented by Liam Sorsby, the most efficient option is likely to check if the parameter is set from your application, and modify the query string accordingly. If the parameter is not set, the query does not have a WHERE clause; if it is set, then WHERE user_id =:user_id .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM