首页 > 数据库技术 > 详细

php数组拼接mysql in语句

时间:2021-09-12 13:34:17      阅读:31      评论:0      收藏:0      [点我收藏+]

数据分析

通常php后端接收前端1个数组参数时通常为:

  • 数组:[‘aa‘,‘bb‘,‘cc‘]

  • json数组字符串: ‘["aa","bb","cc"]‘

  • 逗号隔开的字符串:‘aa,bb,cc‘

先统一转为数组。

#json字符串转数组
$str = ‘["aa","bb","cc"]‘;
$arr = json_decode($str,true);
# [‘aa‘,‘bb‘,‘cc‘]

#逗号隔开字符串转数组
$str = ‘aa,bb,cc‘;
$arr = explode(‘,‘,$str);
# [‘aa‘,‘bb‘,‘cc‘]

php数组拼接 in语句

mysql in 使用

  • 数值:select * from order where status in(1,2,3);

    数值直接使用implode 将数组[1,2,3],转为字符串1,2,3,拼接即可

    $arr = [1,2,3];
    $str = implode($arr,‘,‘);
    # 1,2,3
    
    $sql = "select * from order where status in({$str})";
    # select * from order where status in(1,2,3)
    
  • 字符串:select * from order where status in(‘waitbuyerpay‘,‘waitsellersend‘,‘waitbuyerreceive‘);

    字符串使用implode($arr,‘,‘)转成字符串为waitbuyerpay,waitsellersend,waitbuyerreceive拼接的sql是有错误的

    可以implode($arr,"‘,‘")转成waitbuyerpay‘,‘waitsellersend‘,‘waitbuyerreceive再在字符串两边拼上

    $arr = [‘waitbuyerpay‘,‘waitsellersend‘,‘waitbuyerreceive‘];
    $str = implode($arr,"‘,‘");
    # waitbuyerpay‘,‘waitsellersend‘,‘waitbuyerreceive
    
    
    $sql = "select * from order where status in(‘{$str}‘)";
    # select * from order where status in(‘waitbuyerpay‘,‘waitsellersend‘,‘waitbuyerreceive‘)
    

php数组拼接mysql in语句

原文:https://www.cnblogs.com/mg007/p/15247248.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!