cleaning a post URL from an Array

75 views Asked by At

Here is my code :

$query = "SELECT first_name, surname, email FROM app2";
$result = mysql_query($query) or die(mysql_error());

 $url = "https://test.com?"; // Where you want to post data
 while($row = mysql_fetch_array($result)) {
        $input = "";
        foreach($row as $key => $value) $input .= $key . '=' . urlencode($value) . '&';
        $input = rtrim($input, '& ');

        $ch = curl_init();                    // Initiate cURL
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_POST, true);  // Tell cURL you want to post something
        curl_setopt($ch, CURLOPT_POSTFIELDS, $input); // Define what you want to post
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); // Return the output in string format
        $output = curl_exec ($ch); // Execute

        curl_close ($ch); // Close cURL handle

        var_dump($output); // Show output
    }

The problem is the data ($input) come out like this :

0=Lucky&first_name=Lucky&1=Dube&surname=Dube

It should be like this :

first_name=Lucky&surname=Dube
2

There are 2 answers

2
Kevin On BEST ANSWER

No need to build your query on your own. First off, just use _assoc()* function flavor, then use http_build_query on that row array batch, then feed it. It will construct the query string for you. No need to append each element with & with your foreach. Rough example:

$url = "https://test.com"; // Where you want to post data

while($row = mysql_fetch_assoc($result)) {

    $input = http_build_query($row);
    $ch = curl_init(); // Initiate cURL
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_POST, true);  // Tell cURL you want to post something
    curl_setopt($ch, CURLOPT_POSTFIELDS, $input); // Define what you want to post
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); // Return the output in string format
    $output = curl_exec ($ch); // Execute

    curl_close ($ch); // Close cURL handle
}
0
monxas On

Try changing

while($row = mysql_fetch_array($result)) {

with

while($row = mysql_fetch_assoc($result)) {

mysql_fetch_assoc returns only the associative array.