21
17

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

[php]配列データをimplodeで区切り、クオーテーションで囲む

Last updated at Posted at 2015-08-03

自分用メモ
SQLのIN句をphp使って例えば以下のように書きたいとき、
IN句内のデータをどうやって入れようかという話。

SELECT * FROM test_table where id IN("a0001","a0002","a0003");

#結論

index.php
$id_list = array('a0001','a0002','a0003');
$sql = 'SELECT * FROM test_table where';

// ↓こう書く
$sql .= ' id IN("'.implode('","',$id_list).'")';

#思考手順

index.php
// 1.配列データとsql用意
$id_list = array('a0001','a0002','a0003');

// 2.implodeで配列をカンマで区切って文字列にする
// a0001,a0002,a0003
$in = implode(',',$id_list);

// 3.区切りのカンマをクオーテーションで囲む
// a0001","a0002","a0003
$in = implode('","',$id_list);

// 4.implodeをクオーテーションで囲む
// "a0001","a0002","a0003"
$in = '"'.implode('","',$id_list).'"'; 

// 5.in()で囲む
// IN("a0001","a0002","a0003")
$sql = ' IN('.$in.')';

21
17
1

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
21
17

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?