从数组中清理 post URL

cleaning a post URL from an Array

这是我的代码:

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

问题是数据($input)是这样出来的:

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

应该是这样的:

first_name=Lucky&surname=Dube

无需自行构建查询。首先,只需使用 _assoc()* function flavor,然后对该行数组批次使用 http_build_query,然后输入它。它将为您构建查询字符串。无需在 foreach 后附加带有 & 的每个元素。粗略示例:

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

尝试更改

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

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

mysql_fetch_assoc returns 只有关联数组。