I have a form which sends bulk messages to customers, on clicking submit button, it saves the messages in the DB before sending, but the inserting process takes about 2 mins to insert 3000 records, How can I reduce the insertion time or how can I process the data in the background to avoid the user waiting for the process to complete. I have tried several options on stack overflow with no success. I am on a shared hosting. here is my code
<?php
if(isset($_POST['submit'])){
$date = date("D, F d, Y h:i:sa");
$phones = $_POST['recipient_phones']; //get phone numbers from textarea
$phones = trim($phones,",\r\n\t\r\n/\s+/\0\x0B]/"); //do some regex
$phones = multiexplode(array(","," ","\n","r\n",".","|",":"),$phones);//reformat and convert to array
$sender = $_POST['sender_id']; //Get Sender ID input field
$message = $_POST['message']; //Get Message input field
$time = $_POST['sc_time']; //Get time input field
ob_end_clean();
ignore_user_abort();
ob_start();
header("Connection: close");
// echo json_encode($out);
header("Content-Length: " . ob_get_length());
ob_end_flush();
flush();
foreach($phones as $phone){
$data = array("sender" => "$sender","phone" => "$phone", "message" => "$message", "user_id" => "$user_id","time_submitted" => "$date");
$qry = Insert('crbsms_queue',$data);
$_SESSION['msg']="10";
echo "<script>location.href='$url?success=yes';</script>";
exit
}
# Insert Data
function Insert($table, $data){
global $mysqli;
//print_r($data);
$fields = array_keys( $data );
$values = array_map( array($mysqli, 'real_escape_string'), array_values( $data ) );
//echo "INSERT INTO $table(".implode(",",$fields).") VALUES ('".implode("','", $values )."');";
//exit;
mysqli_query($mysqli, "INSERT INTO $table(".implode(",",$fields).") VALUES ('".implode("','", $values )."');") or die( mysqli_error($mysqli) );
}