PHP using CURL inside while loop

BR
BR used Ask the Experts™
on
Dear Experts,
I connect a server using CURL to send SMS messages.

First, I select the data from my database and send it to the selected numbers.
Then I put it inside a while loop to send it to every number using CURL.

I use below code,

but I wonder which part should I use inside the while loop?
Do I have to initialize CURL for every time?
Which part should I use inside the while loop?

if ($result->num_rows > 0) {

while($row = $result->fetch_assoc()) {
        	
$curl = curl_init();

curl_setopt_array($curl, array(
  CURLOPT_URL => "xxxxxxx",
  CURLOPT_RETURNTRANSFER => true,
  CURLOPT_ENCODING => "",
  CURLOPT_MAXREDIRS => 10,
  CURLOPT_TIMEOUT => 30,
  CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
  CURLOPT_CUSTOMREQUEST => "POST",
  CURLOPT_POSTFIELDS => "{\r\n\t\"xxxxx\"\r\n\t}\r\n}",
  CURLOPT_HTTPHEADER => array(
    "accept: application/json",
    "authorization: ".$kullanici_sifre."",
    "content-type: application/json"
  ),
));

$response = curl_exec($curl);
$err = curl_error($curl);

curl_close($curl);

if ($err) {
  echo "cURL Error #:" . $err;
} else {
  echo $response;
}

}
}

Open in new window

Comment
Watch Question

Do more with

Expert Office
EXPERT OFFICE® is a registered trademark of EXPERTS EXCHANGE®
Most Valuable Expert 2018
Distinguished Expert 2018
Commented:
Nothing in your while() loop actually uses the $row from the loop, so why would you want anything to do with cURL inside it.

If you do want to set various options based on your loop, then you should be able to init the cURL request before the loop and then just set the specific options inside:

$curl = curl_init();

curl_setopt_array($curl, array(
    ...
    ...
    ...
));

while($row = $result->fetch_assoc()) {

    curl_setopt ( $curl, SomeOption, "someValue" );
    $response = curl_exec($curl);
    $err = curl_error($curl);

}

curl_close($curl);

Open in new window

BRDigital Marketing

Author

Commented:
thank you

Do more with

Expert Office
Submit tech questions to Ask the Experts™ at any time to receive solutions, advice, and new ideas from leading industry professionals.

Start 7-Day Free Trial