1

My code is below.. using php to take data from SQL and post it using cURL. My question is after cURL encounters an error, is there a way to ignore it (or send it to a log file) and continue with the next line in the array? Currently as soon as it finds an error it's killing it.

<?php

// SQL connection stuff...

// fetch data from sql
$sql = "Select * from tablename";
$result = sqlsrv_query($conn, $sql) or die("Error in Selecting " . sqlsrv_error($conn));

// convert result to array
$array = array();
while($row = sqlsrv_fetch_array($result, SQLSRV_FETCH_ASSOC)) {

    $array[] = $row;
}       
foreach($array as $data) {
$post = http_build_query($data) . "\n";

//echo $post; //save this for testing later
}


// API url
$url = "www.example.com";

// initiate cURL
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_POSTFIELDS, $post);
curl_setopt($ch, CURLOPT_POST, true);

// execute POST
$response = curl_exec($ch);

// display errors
$status = curl_getinfo($ch, CURLINFO_HTTP_CODE);
echo $status."=response"."</br>";

curl_close($ch);

// close connection
sqlsrv_close($conn) 

?>
3
  • Your curl request is only going to be executed once regardless of success or failure, as there is no looping construct here at all. Commented Aug 25, 2015 at 19:59
  • I'm realizing that now... but not sure why when I just echo it it's showing me all of the results. Before I added the foreach it was only returning the first result so I thought the curl would now loop too but obviously I'm mistaken. Commented Aug 25, 2015 at 20:07
  • Ugh, because I've got the foreach in the echo but not the curl... dang I need a nap. Thanks to both of you! Commented Aug 25, 2015 at 20:25

1 Answer 1

2

Wrap your code inside try {} ... catch {} to allow you to handle any exceptions:

try {
   // your curl execution
} catch (Exception $e) { 
   // log or do what you want
}
Sign up to request clarification or add additional context in comments.

2 Comments

Thanks! I figured it'd be something easy like that. Quick follow up question if that's ok... it appears to be now that I also have an error in getting it to loop through them in general. If I do an "echo $post" as I have commented out currently I see all of them, but in running the cURL it's only doing the first one still?
it seemes to me that $array is not array

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.