简体   繁体   English

如何将数组的内容输出为逗号分隔的字符串?

[英]How do you output contents of an array as a comma separated string?

I would like to convert an array if IDs, into a string of comma separated values, to use in a MySQL UPDATE query. 我想将ID数组转换成逗号分隔值的字符串,以便在MySQL UPDATE查询中使用。 How would I do this? 我该怎么做?

implode(',', $array);

记住要逃避值:

'"' . implode('","', array_map('mysql_real_escape_string', $data)) . '"'

Make sure you pass the results through mysql_real_escape_string() before executing your query. 在执行查询之前,请确保通过mysql_real_escape_string()传递结果。 This should prevent sql injection if you use implode() as others suggest. 如果您像其他人建议的那样使用implode(),这应该可以防止sql注入。

And as nickf mentions, always check to make sure the array isn't empty or null first, and handle those cases. 正如nickf所提到的,请务必先检查以确保数组不为空或为null,然后处理这些情况。 Since you are only dealing with int's, it wouldn't hurt to put some type checking in your assignments, otherwise you'll get sql errors if a string slips in somehow. 由于您只处理int,因此在分配中进行一些类型检查不会有什么坏处,否则如果字符串以某种方式滑入,则会出现sql错误。

Often this type of situation is people building an array from another table for use in a 2nd query.. If this is the case you can use a subquery to accomplish this. 通常,这种情况是人们从另一个表中构建一个数组以供第二个查询使用。如果是这种情况,则可以使用子查询来完成此操作。

Eg. 例如。 UPDATE Table SET Column = Value WHERE ID IN ( SELECT ID FROM Table2 WHERE CONDITIONS ) 更新表SET列=值WHERE ID IN(从Table2的SELECT ID中的WHERE条件)

This is probably better if all ids should be numerical. 如果所有ID均为数字,则可能会更好。 Check that it consists of at least one integer with 检查它是否包含至少一个整数

$ids = array_filter($ids, 'is_int');
if (!$ids) {
    //no valid ids returned.
    die('or something');
}
$sql .= '(' . implode(',', $ids) . ')';

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM