$sql_query_posts = "SELECT * FROM `posts`";
$sql_form_permission = mysql_query("SELECT * FROM `integrations` WHERE `rank_id`='$user_level' AND `mode`='form_per'");
if ( mysql_num_rows($sql_form_permissions) > 0 ) {
现在我正在努力的部分:
$sql_query_posts .= " IN (";
while ( $row_form_permissions = mysql_fetch_assoc($sql_form_permissions) ) {
$sql_query_posts .= $row_form_permissions['form_id'] . ",";
}
$sql_query_posts .= ")";
}
我希望输出类似于:
SELECT * FROM `posts` IN (4, 3, 2)
但上面的代码给出了如下输出:
SELECT * FROM `posts` IN (4, 3, 2,)
所以我必须在最后摆脱逗号。如何确保脚本禁用最后一行的逗号。
答案 0 :(得分:4)
我会使用implode
:
$post_ids = array();
while ( $row_form_permissions = mysql_fetch_assoc($sql_form_permissions) ) {
$post_ids[] = $row_form_permissions['form_id'];
}
$sql_query_posts .= " IN (" . implode(",", $post_ids) . ")";
答案 1 :(得分:2)
像这样使用$sql_query_posts = substr($sql_query_posts, 0, -1);
:
$sql_query_posts .= " IN (";
while ( $row_form_permissions = mysql_fetch_assoc($sql_form_permissions) ) {
$sql_query_posts .= $row_form_permissions['form_id'] . ",";
}
$sql_query_posts = substr($sql_query_posts, 0, -1);
$sql_query_posts .= ")";
只是为了解决你最终没有获取记录(一个空数组)的情况,使用implode()可能更明智,就像这样(我总是这样使用它):
$ins = array();
while ( $row_form_permissions = mysql_fetch_assoc($sql_form_permissions) ) {
$ins[] = $row_form_permissions['form_id'];
}
$sql_query_posts .= sprintf(' IN (%s)', implode(',', $ins));
答案 2 :(得分:2)
在我看来,比建议更漂亮的方式是:
$forms = array();
while ( $row_form_permissions = mysql_fetch_assoc($sql_form_permissions) )
$forms[] = $row_form_permissions['form_id'];
$sql_query_posts .= " IN (".implode(",",$forms).")";
答案 3 :(得分:0)
您可以使用substr
关闭逗号。像这样:
$sql_query_posts .= " IN (";
while ( $row_form_permissions = mysql_fetch_assoc($sql_form_permissions) ) {
$sql_query_posts .= $row_form_permissions['form_id'] . ",";
}
$sql_query_posts = substr($sql_query_posts, 0, -1); // <- this is the new line
$sql_query_posts .= ")";
}
答案 4 :(得分:0)
作为substr
的替代,您还可以使用trim
删除逗号。
$sql_query_posts = trim($sql_query_posts, ',') . ')';
修剪比substr更安全,因为你可以将它限制为一个确切的字符或一组字符。
答案 5 :(得分:0)
我会使用trim或(rtrim)函数就是这种情况(http://php.net/manual/en/function.trim.php) 你给它一个字符串,并使用它的第二个参数指定额外的字符,并为你清理它。