Number not increasing with each refresh of page - php

What I am trying to do every time the page is refreshed $insertedBookings should be adding how many were entered so that it becomes a total however its still staying at 6 there is a total of 11 items to be entered.
Code Updated:
$insertedBookings = 0;
foreach($json->data as $row)
{
if (!in_array($row->guestEmail, $emails) && date('Y-m-d', strtotime($row->startDate)) == date('Y-m-d'))
{
$insertedBookings ++;
$guests[] = array(
'FirstName' => $row->guestFirstName,
'LastName' => $row->guestLastName,
'email' => $row->guestEmail,
'country' => $row->guestCountry,
'check-in_date' => $row->startDate,
'check-out_date' => $row->endDate,
);
$emails[] = $row->guestEmail;
}
}
// Insert to IF HERE
if (!isset($_SESSION["totalInsertedBookings"]))
{
$_SESSION["totalInsertedBookings"] = $insertedBookings;
}
$currentInsertedBooking = $_SESSION["totalInsertedBookings"];
**Code:**
$insertedBookings = 0;
foreach($json->data as $row)
{
if (!in_array($row->guestEmail, $emails) && date('Y-m-d', strtotime($row->startDate)) == date('Y-m-d'))
{
$guests[] = array(
'FirstName' => $row->guestFirstName,
'LastName' => $row->guestLastName,
'email' => $row->guestEmail,
'country' => $row->guestCountry,
'check-in_date' => $row->startDate,
'check-out_date' => $row->endDate,
);
$emails[] = $row->guestEmail;
$insertedBookings = count($guests);
}
}
// Insert to IF HERE
if (!isset($_SESSION["totalInsertedBookings"]))
{
$_SESSION["totalInsertedBookings"] = $insertedBookings;
}
$currentInsertedBooking = $_SESSION["totalInsertedBookings"];

Because count($guests) is counting the number of elements in the $guests array which is 6 (FirstName, LastName, etc.).

Related

Insert data from excel (xlsm,xls) in laravel (cyber-duck)

Currently I can get the json data from my excel file with format like this
sample.xlsx
$excel = Importer::make('Excel');
$excel->hasHeader(true);
$excel->load($savePath.$fileName);
$collection = $excel->getCollection();
if(sizeof($collection[1]) == 5)
{
return $collection;
}
else
{
return redirect()
->back()
->with(['errors'=> [0=> 'Please provide date in file according to your format.']])
->with('modal',$modal);
}
output
[{"id":1,"first_name":"j.doe17","last_name":"Jun Doe","email":"j.doe#gmail.com","birthdate":{"date":"1996-09-07 00:00:00.000000","timezone_type":3,"timezone":"Asia\/Taipei"}},{"id":2,"first_name":"j.doe18","last_name":"Jun Doe","email":"jan.doe#gmail.com","birthdate":{"date":"1996-09-07 00:00:00.000000","timezone_type":3,"timezone":"Asia\/Taipei"}}]
Now I'm trying to use this code, just insert those json data to my database table > tbl_sampleimport
foreach ($collection->toArray() as $key => $value) {
foreach ($value as $row) {
$insert_data[] = array(
'first_name' => $row['first_name'],
'last_name' => $row['last_name'],
'email' => $row['email'],
'birthdate' => $row['birthdate'],
'created_at' => now(),
'updated_at' => now(),
);
}
}
DB::table('tbl_sampleimport')->insert($insert_data);
My Table tbl_sampleimport
But this gives me an error like this Illegal string offset 'first_name'
Laravel : v5.8.*
cyber-duck/laravel-excel
use json_decode() to convert into array
$arr = json_decode($collection, true);
foreach($arr as $row) {
$insert_data[] = array(
'first_name' => $row['first_name'],
'last_name' => $row['last_name'],
'email' => $row['email'],
'birthdate' => $row['birthdate']['date'],
'created_at' => now(),
'updated_at' => now(),
);
}

PHP/MySQL - CSV parse with functions results in "METHOD NOT ALLOWED" when over 28 rows are uploaded

I have created a PHP CSV parser. My customer uploads a csv file there with data of his customers, the csv is exploded into rows and further into cells.
Finally the cells are uploaded to corresponding MySQL database, sent via XML SoapCall to an external database and in the end echoed onto documents body with statuses of every row sent.
It works perfectly fine for up to 28 rows in CSV, but whenever there are more rows to be added a
500 Internal Error
The server encountered an internal error and could not complete your request.
pops in and would stop the update/soapcall/echo loop.
Any ideas what may this be caused by?
Memory cache limit is set to 256mb while max uploaded file size is 64mb, dont think any of those have been exceeded.
EDIT1:
It actually seems like the problem were spaces in some of the cells. Now however it would stop at row 28 and bring error 500 Internal Error
The server encountered an internal error and could not complete your request..
Any ideas?
EDIT2 code:
<?php
if (isset($_POST['submit'])) {
if (isset($_FILES["filetoparse"]['tmp_name'])) {
} else {
die("Błąd wgrywania pliku");
}
$file = file_get_contents($_FILES["filetoparse"]['tmp_name']);
if (isset($file)) {
} else {
die("Błąd odczytu pliku.");
}
function array_to_xml($array, &$xml) {
foreach($array as $key => $value) {
if(is_array($value)) {
if(!is_numeric($key)){
$subnode = $xml->addChild("$key",'','');
array_to_xml($value, $subnode);
} else {
array_to_xml($value, $xml);
}
} else {
$xml->addChild("$key","$value",'');
}
}
};
$echo = "";
$rows = explode("\n", $file);
array_shift($rows);
foreach($rows as $row => $data) {
$row_data = explode(';', $data);
$info[$row]['name'] = $row_data[0];
$info[$row]['city'] = $row_data[1];
$info[$row]['postalcode'] = $row_data[2];
$info[$row]['pesel'] = $row_data[3];
$info[$row]['phone'] = $row_data[4];
$info[$row]['amount'] = $row_data[5];
$info[$row]['sex'] = $row_data[6];
$name = $info[$row]['name'];
$city = $info[$row]['city'];
$postcode = $info[$row]['postalcode'];
$pesel = $info[$row]['pesel'];
$phone = $info[$row]['phone'];
$price = $info[$row]['amount'];
$xmlsex = $info[$row]['sex'];
$xmlsexx = preg_replace('/\s+/', '', $xmlsex);
$names = explode(' ', $name);
$firstname = $names[0];
$lastname = $names[1];
if (empty($pesel)) {
continue;
}
// Api Fines.pl module
$client = new SoapClient("SOME_API");
$contract = array(
'product' => array(
'prefix' => 'MOP',
),
'participants' => array(
'customers' => array(
'main_borrower' => array(
'personal_data' => array(
'pesel' => $pesel,
'firstname' => $firstname,
'lastname' => $lastname,
'sex' => $xmlsexx,
),
'contact_data' => array(
'addresses' => array(
'address' => array(
'type' => 'registered',
'street_name' => $city,
'block_number' => '1',
'flat_number' => '1',
'postal_code' => $postcode,
'city' => $city,
),
),
'phones_mobile' => array(
'phone_mobile' => array(
'type' => 'personal',
'number' => $phone,
),
),
),
'incomes' => array(
'income' => array(
'type' => 'employment',
'main_income' => 'true',
'fixed_term_contract' => 'false',
'paychecks' => array(
'paycheck' => array(
'amount_net' => array(
'amount' => $price,
'currency' => 'PLN',
),
'type' => 'base',
),
),
),
),
),
),
),
);
$xml = new SimpleXMLElement("<?xml version=\"1.0\" encoding=\"UTF-8\"?><sof:Contract xmlns:s=\"http://www.fines.pl/simple\" xmlns:sof=\"http://www.fines.pl/sof\" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xsi:schemaLocation=\"http://www.fines.pl/sof model.xsd \"></sof:Contract>");
array_to_xml($contract, $xml);
$parameters = array(
'user_login' => 'XXX',
'user_password' => 'XXX',
'contract' => $xml->asXML(),
);
$response = $client->newApplication($parameters);
$responsearray = get_object_vars($response);
if ($response->success) {
$finesaccepted = "Tak - " . $response->number_sof;
} else {
$finesaccepted = "Nie - " . $response->messages->message->text;
}
$finesaccepted = str_replace("'", "", $finesaccepted);
//into database
$mysqli = new mysqli('XXX', 'XXX', 'XXX', 'XXX');
$ip = $_SERVER['REMOTE_ADDR'];
$date = date("U");
if ($xmlsexx == 'male') {
$querysex = "Mężczyzna";
} else {
$querysex = "Kobieta";
}
$insertquery = "INSERT INTO x_form (ref_id, date, firstname, lastname, check_rules, ip_adres, email, phone, type, company, nip, postcode, city, amount, income, pesel, sex, isfb, finesaccepted) VALUES ('$date', '$date', '$firstname', '$lastname', '1', '$ip', 'brak', '$phone', '4', NULL, NULL, '$postcode', '$city', NULL, '$price', '$pesel', '$querysex', '2', '$finesaccepted')";
$echo .= $firstname . " " . $lastname . " - Dodano do bazy. Przyjęto w Fines: " . $finesaccepted . "<br>";
$mysqli->query($insertquery);
sleep(1);
}
}
?>

Removing an Array Object if key is found

How can I remove a whole array object if a $key=>value matches?
For example in my data I have ["endDate"]=> string(10) "2017-06-24" and if that date matches todays date('Y-m-d') I would like the whole object bock to be removed from the $row
Code:
foreach ($json->data as $row)
{
$date = date('Y-m-d');
if($row->endDate == $date){
$search = array_search($date, array_column('endDate', $row));
unset($row[$search]);
if (!in_array($row->guestEmail, $emails) && date('Y-m-d', strtotime($row->startDate))== date('Y-m-d'))
{
$guests[] = array(
'FirstName' => $row->guestFirstName,
'LastName' => $row->guestLastName,
'email' => $row->guestEmail,
'country' => $row->guestCountry,
'check-in_date' => $row->startDate,
'check-out_date' => $row->endDate,
);
$emails[] = $row->guestEmail;
}
}
}
JSON:
$response = $o->curl(sprintf($url, $propertyID, $pageSize, $pageNumber, $resultsFrom));
$json = json_decode($response);
$date = date('Y-m-d');
foreach ($json->data as $index=> $row){
if($row->endDate == $date) unset($json->data{$index});
}
foreach ($json->data as $row){
if (!in_array($row->guestEmail, $emails) && date('Y-m-d', strtotime($row->startDate))== date('Y-m-d'))
{
$guests[] = array(
'FirstName' => $row->guestFirstName,
'LastName' => $row->guestLastName,
'email' => $row->guestEmail,
'country' => $row->guestCountry,
'check-in_date' => $row->startDate,
'check-out_date' => $row->endDate,
);
$emails[] = $row->guestEmail;
}
}
You may also consider just skipping to the next iteration, since it looks like you are building a guest email list and are not trying to modify the source of the json feed.
$date = date('Y-m-d');
foreach ($json->data as $row){
if($row->endDate == $date) {
continue;
}
if (!in_array($row->guestEmail, $emails) && date('Y-m-d', strtotime($row->startDate))== date('Y-m-d'))
{
$guests[] = array(
'FirstName' => $row->guestFirstName,
'LastName' => $row->guestLastName,
'email' => $row->guestEmail,
'country' => $row->guestCountry,
'check-in_date' => $row->startDate,
'check-out_date' => $row->endDate,
);
$emails[] = $row->guestEmail;
}
}
Between the two options I pose, the second one requires less code and will yield slightly faster execution times.
If you place an ampersand before $row in your foreach you can change $json->data directly. From what you wrote, I think I understand your question and this may be what you need.
foreach ($json->data as &$row)
{
$date = date('Y-m-d');
if ($row->endDate == $date) {
$search = array_search($date, array_column('endDate', get_object_vars($row)));
unset($row[$search]);
if (!in_array($row->guestEmail, $emails) && date('Y-m-d', strtotime($row->startDate))== date('Y-m-d'))
{
$guests[] = array(
'FirstName' => $row->guestFirstName,
'LastName' => $row->guestLastName,
'email' => $row->guestEmail,
'country' => $row->guestCountry,
'check-in_date' => $row->startDate,
'check-out_date' => $row->endDate,
);
$emails[] = $row->guestEmail;
}
}
}
If not then rephrase your question so I might provide the answer you need.

How can I implement insert_batch active record in codeigniter in inserting multiple values?

I am currently working on adding multiple requests in single click using CodeIgniters insert_batch.
This is my model
function add_request($data) {
$this->db->insert_batch('requests',$data);
}
This is my controller
if($_POST) {
$code = $this->input->post('code');
$about = $this->input->post('about');
$qnty = $this->input->post('quantity');
$budget = $this->input->post('budget');
$sched = $this->input->post('sched');
for($i = 0; $i < count($code); $i++) {
$data[$i] = array(
'code' => $code,
'description' => $_POST['desc'],
'qnty' => $qnty,
'budget' => $budget,
'sched' => $sched,
'from' => $this->session->userdata('user_id'),
'status' => 'Pending',
'about' => $about
);
$this->request->add_request($data[$i]);
}
This code doesnt work It only adds blank record.
Consider this code for the controller:
$data = array();
for($i = 0; $i < count($code); $i++) {//build the array
$data[$i] = array(
'code' => $code,
'description' => $_POST['desc'],
'qnty' => $qnty,
'budget' => $budget,
'sched' => $sched,
'from' => $this->session->userdata('user_id'),
'status' => 'Pending',
'about' => $about
);
}
//$data will be a bidimentional array
//pass $data to the model after the looping is done, thus the array is complete
$this->request->add_request($data);

Laravel - prepared statement contains too many placeholders

Im wondering if someone could give me a hand.
I have written an import script, it works fine for a small number of points, but when i start importing large numbers, i get the following error:
General error: 1390 Prepared statement contains too many placeholders
The code that im using to import is as follows:
foreach ( $items as $item ) {
$insert[] = array(
'userid' => User::current()->id,
'lati' => $item[0],
'long' => $item[1],
'streetNumber' => $item[2],
'streetName' => $item[3],
'country' => $item[6],
'state' => $item[5],
'pcode' => $item[7],
'suburb' => $suburb,
'created_at' => new DateTime,
'updated_at' => new DateTime
);
}
if(DB::table('mytable')->insert($insert))
{
return true;
} else {
return false;
}
Any help with figuring out how to fix this would be greatly appreciated.
function addData($items) {
$itemsTemp = [];
if (count > 1000) {
$itemsTemp = array_slice($items, 1000);
$items = array_slice($items, 0, 1000);
}
foreach ( $items as $item ) {
$insert[] = [
'userid' => User::current()->id,
'lati' => $item[0],
'long' => $item[1],
'streetNumber' => $item[2],
'streetName' => $item[3],
'country' => $item[6],
'state' => $item[5],
'pcode' => $item[7],
'suburb' => $suburb,
'created_at' => new DateTime,
'updated_at' => new DateTime
];
}
if (DB::table('mytable')->insert($insert)) {
if ($itemsTemp) {
addData($itemsTemp);
}
} else {
return false;
}
return true;
}

Categories