【问题标题】:php mysql query strings array [duplicate]php mysql 查询字符串数组
【发布时间】:2011-02-07 22:16:09
【问题描述】:

我正在构建一个我在 mysql db 中签入的字符串。

eg:
formFields[] is an array - input1 is: string1
array_push(strings, formFields)
1st string and mysql query looks like this:
"select * from my table where id in (strings)"

formFields[] is an array - input2 is: string1, string2
array_push(strings, formFields)
2nd string and mysql query looks like this:
"select * from my table where id in (strings)"

formFields[] is an array - input3 is: string1, string2,string3
array_push(strings, formFields)
3rd string and mysql query looks like this:
"select * from my table where id in (strings)"

我想在数组中添加单引号和逗号,这样我就有了数组字符串: "select * from my table where id in ('string1', 'string2','string3')"

我尝试使用数组内爆,但仍然没有任何想法?谢谢

【问题讨论】:

    标签: php mysql arrays string


    【解决方案1】:
    'SELECT ... WHERE id IN ("' . implode('","', $strings) . '")';
    

    【讨论】:

    • 效果很好!我想问一个问题,这些点到底在做什么,它们是否像“+”一样将引号与内爆结果粘合在一起?
    【解决方案2】:

    implode() 是解决方案,但您不应忘记转义数据:

    $data = array(...);
    array_walk($data, function(&$elem, $key) {
        $elem = mysql_real_escape_string($elem);
    });
    $sql = 'SELECT ... id IN ("' . implode('", "', $data) . '");';
    

    【讨论】:

      【解决方案3】:
      implode("','",$array);
      

      【讨论】:

      • 这不会在字符串的开头和结尾添加引号。还是谢谢!
      • @Chocho 你也不知道串联吗?那么你迫切需要基本的 PHP 类。
      猜你喜欢
      • 1970-01-01
      • 2014-12-21
      • 1970-01-01
      • 2013-12-15
      • 2014-10-01
      • 1970-01-01
      • 2014-10-11
      • 2010-09-28
      • 2021-01-15
      相关资源
      最近更新 更多