2
$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 ) {

Now the part I'm struggling with:

   $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 .= ")";
    }

I want the output to be something like:

SELECT * FROM `posts` IN (4, 3, 2)

But the code above gives an output like:

SELECT * FROM `posts` IN (4, 3, 2,)

So I have to get rid of the comma at the end. How can I make sure the script disables the comma at the last row.

4

6 回答 6

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) . ")";
于 2013-06-09T09:57:07.537 回答
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).")";
于 2013-06-09T09:59:53.477 回答
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));
于 2013-06-09T09:55:22.720 回答
0

作为替代,substr您也可以使用trim去掉逗号。

$sql_query_posts = trim($sql_query_posts, ',') . ')';

Trim 比 substr 稍微安全一些,因为您可以将其限制为精确的字符或字符集。

于 2013-06-09T09:59:37.730 回答
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 .= ")";
}
于 2013-06-09T09:56:29.290 回答
0

我会使用修剪或(rtrim)函数是这种情况(http://php.net/manual/en/function.trim.php)你给它字符串,并使用它的第二个参数指定额外的字符,它会清理给你。

于 2013-06-09T11:20:14.480 回答