LoginSignup
0
0

【SQL】WHERE IN で入力した順番でかつ、エスケープして取得する

Last updated at Posted at 2023-05-16

CodeIgniter3とPHPとSQLの混合なのであまり参考にはならないかもです

コード1

    $ids = array_map('intval',explode(',',$ids));
    $hold_id = array_merge([$ids],$ids);

    global $wpdb;
    $sql="
    SELECT
        id,name
    FROM table 
    WHERE id IN ? 
    ORDER BY FIELD(id,".(implode(',',array_fill(0,count($ids),'?'))).") 
    ";
                                   ↓ここ[]を外す
    $data = $wpdb->db->query($sql,$hold_id)->result_array();
                                   ↑ここ[]を外す

    return $data;
}

コード2

    $master_ids = array_map('intval',explode(',',$ids));

    global $wpdb;
    $sql ="
    SELECT 
    id,name
    FROM table 
    WHERE id IN ? 
    ";
    $data = $wpdb->db->query($sql,[$master_ids])->result_array();

    if(empty($data)) [];

    $data = array_column($data, null, 'id');

    $res = [];
    foreach($master_ids as $key => $id){
        if(!empty($data[$id])){
            $res[] = [
                'id' => $data[$id]['id'],
                'name' => $data[$id]['name'],
            ];
        }
    }
0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0