Send data in array in php
I collected the data and created an array as well:
Array
(
[0] => Array
(
[id] => 1
[name] => Martin
[surname] => test
[email] => martin@gmail.com
[dob] => 2015-02-24
)
[1] => Array
(
[id] => 2
[name] => Kary
[surname] => paulman
[email] => kary@gmail.com
[dob] => 2015-06-26
)
)
I have multiple entries in this array.
I want to post each entry in an array at www.recieve.com where it will respond "true" if the message was successful and "false" if it failed.
I've researched interent and I don't even know where to start.
So far my code looks like this (this is for array only)
$query = "SELECT * FROM applicants";
$result = mysql_query($query) or die(mysql_error());
while($row = mysql_fetch_assoc($result)){
$res[] = $row;
}
echo "<pre>"; print_r($res); echo "</pre>";
I have tryed this and it is not working :
//Build my array
$query = "SELECT * FROM applicants";
$result = mysql_query($query) or die(mysql_error());
while($row = mysql_fetch_assoc($result)){
$res[] = $row;
}
//URL to post to
$url = 'https://theurl.com?';
//url-ify the data for the POST
foreach($res as $key=>$value) { $fields_string .= $key.'='.$value.'&'; }
rtrim($fields_string, '&');
$ch = curl_init();
//set the url, number of POST vars, POST data
curl_setopt($ch,CURLOPT_URL, $url);
curl_setopt($ch,CURLOPT_POST, count($fields));
curl_setopt($ch,CURLOPT_POSTFIELDS, $fields_string);
//execute post
$result = curl_exec($ch);
//close connection
curl_close($ch);
+3
source to share
2 answers
Use Curl and How It Is
$ch = curl_init(); // initiate curl
$url = "http://www.somesite.com/curl_example.php"; // where you want to post data
curl_setopt($ch, CURLOPT_URL,$url);
curl_setopt($ch, CURLOPT_POST, true); // tell curl you want to post something
curl_setopt($ch, CURLOPT_POSTFIELDS, "var1=value1&var2=value2&var_n=value_n"); // 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
?>
Use your array in: curl_setopt ($ ch, CURLOPT_POSTFIELDS
0
source to share
There are two problems with your cURL request that I see:
- You are not encoding the values โโcorrectly for use in the query string
-
$fields
- undefined.
You can solve this using for example:
// make sure the values are encoded correctly:
$fields_string = http_build_query($res);
$ch = curl_init();
//set the url, number of POST vars, POST data
curl_setopt($ch,CURLOPT_URL, $url);
// you need the count of your `$res` variable here:
curl_setopt($ch,CURLOPT_POST, count($res));
curl_setopt($ch,CURLOPT_POSTFIELDS, $fields_string);
//execute post
$result = curl_exec($ch);
//close connection
curl_close($ch);
Also note that you don't need a question mark at the end of the url. I don't know if this would cause problems, but you should probably just remove this:
$url = 'https://theurl.com';
+1
source to share