2013-12-10 17 views
0

我一直在和开发人员讨论下面的代码。它是一个函数,它将采用标量整数或标量整数的一维数组作为$ comment_id。目标是将诸如$comment_id = 16;$comment_id = '16';$comment_id = array(1, '2', 3, '4', 5, ...)$comment_id = array(1, '2', 3, '4', 5, ...)之类的东西转换为$id_string = '1, 2, 3, 4, 5'; $ id_string将在SQL WHERE NOT IN子句中用于从结果中排除某些主键。该功能将在我们的应用程序中广泛使用,所以重要的是它运行速度快,但出于安全原因也是完整的。PHP使用完整性令牌化逗号列表的最简单方法

鉴于上面的例子,我问1.这个函数将做我已经完成的任务,2.如果没有,那么你可以提供一个替代方案。感谢您的时间。

代码:

public function int_or_array_to_comma_list($comment_id) 
{ 
    if(! is_array($comment_id)) 
    { 
     if(! is_numeric($comment_id)) throw new Exception(); 

     $comment_id = intval($comment_id); 

     // is $comment_id a integer? 
     if($comment_id === 0) throw new Exception(); 

     $values = array($comment_id); 
    } 
    else 
    { 
     $values = $comment_id; 
    } 

    if(empty($values)) throw new Exception(); 

    $id_string = ''; 
    for($i = 0; $i <= count($values); $i++) 
    { 
     // does the passed array keys follow the 0, 1, 2, 3, 4, 5, ... pattern? 
     if(! isset($values[$i]) OR ! is_numeric($values[$i])) throw new Exception; 

     $values[$i] = intval($values[$i]); 

     // is $comment_id a integer? 
     if(0 === $values[$i]) throw new Exception(); 

     // build comma list, if final array value exlude comma 
     $id_string .= ($i !== count($values))? $values[$i] . ', ' : $values[$i]; 
    } 

    return $comment_id; 
} 
+0

但你从来没有辩论过代码缩进? – bitWorking

+0

这是很好的缩进,我粘贴在这里然后手动在每一行放置四个空格。这毁了格式。我试图添加更多的空间来纠正缩进,但我收到了系统消息,说它看起来不像代码。 –

+0

@MichaelRich。 。 。这与MySQL无关,因此我将删除标签。 –

回答

2

所有上面的代码可以改写如下:

$values = array_map('intval', (array)$comment_id); 

if(count(array_filter($values)) <> count($values)) 
    throw new \Exception(); 

$id_string = implode(',', $values); 

intval()会投非数字字符串为0,array_filter()将删除任何0值,所以如果传递无效ID,则会引发异常。

我想,如果你需要,你可以做更多的验证,就像一滴重复与array_unique(),检查正数等

而且,你可能要准备发言,这样你只需要确保该占位符计数ID的数量相匹配:

$placeholders = rtrim(str_repeat('?,', count($values)), ','); 
$whereSql = sprintf('WHERE NOT IN(%s)', $placeholders); 
+0

这是一个非常了不起的使用PHP功能。感谢您发布此信息。 –

1

应该工作:

function int_or_array_to_comma_list($comment_id) 
{ 
    return implode(',', array_map('intval', explode(',', implode(',', (array)$comment_id)))); 
} 

任何数据库将忽略重复IN子句中的值和无效ID无关紧要,只要搜索列像ID一样是索引的,所以这是一种适用于所有解决方案的解决方案。

intval呼叫将确保无效结果也返回0,所以对于完全无效输入,这意味着所得的查询将类似于SELECT * FROM table WHERE id IN (0)这是很好执行。即使嵌套在数组中的逗号分隔输入的边缘情况也可以很好地处理。

Working sample visible here

相关问题