Question

$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.

Was it helpful?

Solution 2

Use $sql_query_posts = substr($sql_query_posts, 0, -1); like this:

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

Just to address the case when you might end up with no records fetched (an empty array), it would maybe be wiser to use implode(), like this (I always use it like that):

$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));

OTHER TIPS

I would use implode for that:

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

A prettier way, in my opinion, than the suggested is:

$forms = array();
while ( $row_form_permissions = mysql_fetch_assoc($sql_form_permissions) )
  $forms[] = $row_form_permissions['form_id'];

$sql_query_posts .= " IN (".implode(",",$forms).")";

You could just use substr to get the comma off. Like this:

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

As an alternate to substr you can also use trim to get rid of the comma.

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

Trim is slightly safer than substr because you can limit it to an exact character or set of characters.

I would use trim or (rtrim) function is such situations (http://php.net/manual/en/function.trim.php) You give the string to it, and specify the extra character using its second parameter and it cleans it up for you.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top