簡體   English   中英

如何使用數組作為列與mysql表的列聯接?

[英]How to use array as a column to join with a column of mysql table?

我有一個post_ids數組

$ids = array( 
    [0] => 32 
    [1] => 33 
    [2] => 21 
    [3] => 11 
    [4] => 13 
    [5] => 17 
    [6] => 41 
    [7] => 88 
    [8] => 92 
    [9] => 94 
    [10] => 96 
    [11] => 106 
    [12] => 117 
    [13] => 187 
    [14] => 220 
);

我想在數據庫表中獲取一列,其中post_id與上述數組中的id相匹配。 桌子的結構是這樣的

post_id | meta_key | meta_value

目前,我正在使用foreach ($ids as $id)逐一查詢var。 對於大型數據集,這是低效的。 有沒有一種方法可以通過$ ids數組查詢meta_value列?

這不是最有效的方法,但是可以

$idList = implode(",",$ids);

現在您的查詢

$query = "SELECT * FROM posts 
          WHERE post_id IN ($idList);";

至少現在減少到一個查詢

更新:

為了在填充數組時防止SQL注入,請確保您的數據庫輸入是安全的:

// if you are populating your array this way here is the trick
$ids = array();
foreach ($inputValues as $value){
   $ids[] = (int) $value; // this makes sure your input is an integer
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM