hitek
hitek

Reputation: 382

php string formatting?

Here is the code

    $i=0;
while ($row = mysql_fetch_array($result)) 
    {
    $output.="idno".$i."=".urlencode($row['usr_id']).
    '&'."res".$i."=".urlencode($row['responce']).
    '&'."sex".$i."=".urlencode($row['sex']).
    '&'."com1".$i."=".urlencode($row['com1']).
    '&'."com2".$i."=".urlencode($row['com2']);
     $i++;

    }

OUTPUT i get idno is part of com2 string how do I seperate them.

Upvotes: 0

Views: 297

Answers (3)

Tom Haigh
Tom Haigh

Reputation: 57845

Or you could do this:

$array = array();
$i = 0;
while ($row = mysql_fetch_array($result)) {
    $array["idno$i"] = $row['usr_id'];
    $array["res$i"] = $row['responce'];
    //etc.

    $i++;
}

$output = http_build_query($array);

Upvotes: 1

Gumbo
Gumbo

Reputation: 655795

Another solution would be using an array and join its elements afterwards:

$array = array();
$i = 0;
while ($row = mysql_fetch_array($result)) {
    $array[] = "idno$i=".urlencode($row['usr_id']);
    $array[] = "res$i=".urlencode($row['responce']);
    $array[] = "sex$i=".urlencode($row['sex']);
    $array[] = "com1$i=".urlencode($row['com1']);
    $array[] = "com2$i=".urlencode($row['com2']);
    $i++;
}
$output .= implode('&', $array);

Furthermore you could use the argName[] declaration that PHP will convert into an array when receiving such a request query string.

Upvotes: 3

Greg
Greg

Reputation: 321864

You need to add an & when $i is not zero:

   $i=0;
while ($row = mysql_fetch_array($result)) 
        {
    $output .= ($i ? '&' : '') . "idno".$i."=".urlencode($row['usr_id']).
        '&'."res".$i."=".urlencode($row['responce']).
        '&'."sex".$i."=".urlencode($row['sex']).
        '&'."com1".$i."=".urlencode($row['com1']).
        '&'."com2".$i."=".urlencode($row['com2']);
     $i++;

        }

Upvotes: 4

Related Questions