How to validate error and empty result in PHP - php

First, im new in PHP so please bear with me.
Im creating a web service for android, and this is my code :
if($size > 0)
{
$resultArray = array();
foreach($result as $child)
{
if($child)
{
//add to array
$resultArray[] = array('result' => 'true',
'total' => $size,
'id' => $child['id'],
'user_id' => $child['user_id'],
'name' => $child['name'],
'gender' => $child['gender'],
'born_date' => $child['born_date'],
'born_hour' => $child['born_hour'],
'hospital' => $child['hospital']);
}
}
$this->response($resultArray, 200);
}
else
{
$this->response(array('result' => 'false'), 404);
}
I use the size to validate whether the result is OK 200 (has some data) or error 404. However, there is a possibility that the result's size is 0 (no data) but the result is OK (code 200). How to tell the different?
I tried to use boolean variable instead of $size, but its not working.
Thanks for your help.

Related

PHP. Check all elements of an array for a condition

I have such a problem. There is an array of tasks that are added to the queue. The array looks like:
$job_array['gibdd_history'] = [
'result' => $result,
'job_id' => $job_id,
'result_id' => $result_id,
'error_message' => $error_message,
'is_finished' => false,
'response' => [],
];
$job_array['gibdd_dtp'] = [
'result' => $result,
'job_id' => $job_id,
'result_id' => $result_id,
'error_message' => $error_message,
'is_finished' => false,
'response' => [],
];
The task is added to the queue. I need to write a script which will be executed in a circle by calling
$job_array['gibdd_history']['is_finished'] = $request_job->checkRequestJob($job_id');
until there are no elements in $job_array that have is_finished == false.
Also in the array I get the response result with
$request_job->getResult($job_array['gibdd_history']['result_id']);
I thought to do it through while, but I ran into a looping problem. It's not clear how to check that all array elements
$job_array[key]['is_finished'] == true
in order to exit the loop. Like this:
$all_jobs_finished = false;
while ($all_jobs_finished !== true) {
//sleep(1);
foreach ($job_array as $job_key => $job_data) {
if ($job_array[$job_key]['is_finished'] == false) {
list($job_array[$job_key]['is_finished'], $job_status) = $request_job->checkRequestJob($job_array[$job_key]['job_id']);
if ($job_array[$job_key]['is_finished'] == true) {
$job_array[$job_key]['response'] = $request_job->getResult($job_array[$job_key]['result_id']);
}
}
}
$all_jobs_finished = true;
}
Tasks can run for varying amounts of time and out of order. I just need to wait for the end of all tasks and get the result from all tasks by updating the original array $job_array

Rearranging logic that uses multipe foreach conditions

I have some code that takes an rss feed url, expands the rss link and gets the individual links inside that feed xml. After checking if a link exists, i insert it to a table if it does not exist and do nothing if it does. However my code is becoming more unreadable and one more check that requires another foreach it shall be even more unreadable.
This is the code
public function links_cron_job(){
//Get Rss Links
$this->db->select("the_link_itself");
$query = $this->db->get_where("search_engine_links", array("link_type" => "rss"));
foreach ($query->result() as $row){
$url = $row->the_link_itself;
$rss = Feed::loadRss($url);
foreach ($rss->item as $item) {
$this->db->where('the_link_itself',$item->link);
$query3 = $this->db->get('search_engine_links');
if ($query3->num_rows() > 0){
echo 'duplicates are there';
}else{
$data = array(
'link_country' => 'usa',
'the_link_itself' => $item->link,
'link_category' => 'news_website',
'link_added_by' => 'admin',
'link_type' => 'ordinary_link',
'link_local_type' => 'news',
'link_region' => 'countrywide',
'link_city' => 'washington',
'date_added' => $item->timestamp,
'last_updated' => time()
);
$this->db->insert('search_engine_links', $data);
echo 'no duplicates are there';
}
}
}
}
What would be another approach in doing what i am doing?
Normally I would say, just enter a return. But in this case you still might have
work to do in the extra iterations. So in this case at least we know that we are
done with this iteration, so at least we can add a continue statement:
<?php
foreach ($rss->item as $item) {
$this->db->where('the_link_itself',$item->link);
$query3 = $this->db->get('search_engine_links');
if ($query3->num_rows() > 0) {
echo 'duplicates are there';
continue;
}
$data = array(
'link_country' => 'usa',
'the_link_itself' => $item->link,
'link_category' => 'news_website',
'link_added_by' => 'admin',
'link_type' => 'ordinary_link',
'link_local_type' => 'news',
'link_region' => 'countrywide',
'link_city' => 'washington',
'date_added' => $item->timestamp,
'last_updated' => time()
);
$this->db->insert('search_engine_links', $data);
echo 'no duplicates are there';
}

How to convert and insert string value 9,999.99 to float/double in sql using php

I have arrays of data (import from excel) values in string. One of the data are accounting numbers eg: 9,999.99
my sql data type for that accounting numbers is float.
each time I insert the value.. it only store 9 instead 9,999.99
And I plan to store in format 9999.99 (without the comma)
I cannot change the sql data type to string as it will be use for calculations later on.. so how do i convert and store the data?
appreciate your suggestions.
Thanks
This is my code to insert into DB
// To set HMS daily collection
function set_pbb_data($sheetDataPBB)
{
$OK = 0;
$notOK = 0;
$firstElement = true;
foreach ($sheetDataPBB as $value)
{
if ($firstElement) {
$firstElement = false;
}
else {
$dbEntry = array(
'sett_date' => $value[0],
'trans_date' => $value[1],
'card_no' => $value[2],
'card_type' => $value[3],
'trans_curr' => $value[4],
'trans_amt' => $value[5],
'sett_curr' => $value[6],
'sett_amt' => $value[7],
'gross_cur' => $value[8],
'gross_amt' => $value[9],
'mdr' => $value[10],
'mid' => $value[11],
'approval_code' => $value[12],
'status' => $value[13],
'tid' => $value[14],
'batch_no' => $value[15],
'dba' => $value[16],
'trace_no' => $value[17],
'prod_type' => $value[18]
);
if ($value[0] != null){
$this->db->insert('pbb_cc_tbl', $dbEntry);
if ($this->db->affected_rows() > 0) {
$OK++;
}
else {
echo '<script>alert(" '.$value[0].' Already Exist!");</script>';
$notOK++;
}
}
} //end-if
} //end-foreach
if ($this->db->affected_rows() > 0) {
echo '<script>alert("'.$OK.' PBB Data Added Successfully"); </script>';
}
else {
echo '<script>alert("'.$notOK.' PBB Data Already Exist!"); window.history.back();</script>';
}
}
read each row in excel and insert one by one using sql query
insert into database.table (value) values (cast("999,99" as decimal(9,3)));

How to convert Pdf file to byte array in php and send?

I have found pdf to byte array and vice-versa in java,dotnet and python. But i want to convert pdf to byte array in php laravel. I am using "IMUIS" which is accounting software solution and need to sending journal entries from laravel lumen to "IMUIS" for processing.But it gives the error after converting.
"Foutmelding": "Kan een object van het type System.String niet converteren naar het type System.Byte[]."
In english that means
"Error message": "Can not convert a System.String object to the System.Byte [] type."
The documentation is given here:
doc link
Here is the code for it.
public function saveJournal($values = '') {
//echo "adasd";dd();
$partnerKey = $values->input('Partnerkey');
$omgevingscode = $values->input('Environmentcode');
$file = file_get_contents($values->file('Pdffile'));
$str = base64_encode($file);
$options = array(
\WsdlToPhp\PackageBase\AbstractSoapClientBase::WSDL_URL => env('IMUIS_URL'),
\WsdlToPhp\PackageBase\AbstractSoapClientBase::WSDL_CLASSMAP => ClassMap::get(),
);
$login = new \mysdk\ImuisSDK\ServiceType\Login($options);
if ($login->Login(new \mysdk\ImuisSDK\StructType\Login($partnerKey, $omgevingscode)) !== false) {
$sessionid = $login->getResult()->SessionId;
}
$array = [
'BOE' => [
'JR' => '2018',
'PN' => '5',
'DAGB' => 20,
'REK' => 20032,
'TEGREK' => '40',
'FACT' => 0,
'BTW' => 4,
'BEDRBOEK' => 123.45,
'DAT' => '08-05-2018',
'OPM' => 'Anand testing from wsdl',
'BEDRBTW' => 21,
'FACT' => 0,
'OMSCHR' => 'Testing from wsdl api',
'BOEKSTUK' => 2018075
],
'DIGDOS' => [
'FILE' => $str
]
];
$journaalpost = ArrayToXml::convert($array, 'NewDataSet');//convert array to xml string
$create = new \mysdk\ImuisSDK\ServiceType\Create($options);
if ($create->CreateJournaalpost(new \mysdk\ImuisSDK\StructType\CreateJournaalpost($partnerKey, $omgevingscode, $sessionid, $journaalpost)) !== false) {
$jsonResponse = $create->getResult();
} else {
$jsonResponse = $create->getLastError();
}
return $jsonResponse;
}
and here is the response as well:
{
"success": true,
"result": {
"CreateJournaalpostResult": false,
"Journaalpost": "<?xml version=\"1.0\"?>\n<NewDataSet><BOE><JR>2018</JR><PN>5</PN><DAGB>20</DAGB><REK>20032</REK><TEGREK>40</TEGREK><FACT>0</FACT><BTW>4</BTW><BEDRBOEK>123.45</BEDRBOEK><DAT>08-05-2018</DAT><OPM>Anand testing from wsdl</OPM><BEDRBTW>21</BEDRBTW><OMSCHR>Testing from wsdl api</OMSCHR><BOEKSTUK>2018075</BOEKSTUK></BOE><DIGDOS><FILE>JVBERi0xLjMKMyAwIG9iago8PC9UeXBlIC9QYWdlCi9QYXJlbnQgMSAwIFIKL1Jlc291cmNlcyAyIDAgUgovQ29udGVudHMgNCAwIFI+PgplbmRvYmoKNCAwIG9iago8PC9GaWx0ZXIgL0ZsYXRlRGVjb2RlIC9MZW5ndG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"Kan een object van het type System.String niet converteren naar het type System.Byte[]."
}
}
To convert PDF to byte array you will have to read the document using file_get_contents() and then parse it by function unpack().
<?php
public function saveJournal($values = '') {
$partnerKey = $values->input('Partnerkey');
$omgevingscode = $values->input('Environmentcode');
$file = file_get_contents($values->file('Pdffile'));
$byte_array = unpack("C*",$file);
$base64_encode = base64_encode(serialize($byte_array));
$options = array(
\WsdlToPhp\PackageBase\AbstractSoapClientBase::WSDL_URL => env('IMUIS_URL'),
\WsdlToPhp\PackageBase\AbstractSoapClientBase::WSDL_CLASSMAP => ClassMap::get(),
);
$login = new \mysdk\ImuisSDK\ServiceType\Login($options);
if ($login->Login(new \mysdk\ImuisSDK\StructType\Login($partnerKey, $omgevingscode)) !== false) {
$sessionid = $login->getResult()->SessionId;
}
$array = [
'BOE' => [
'JR' => '2018',
'PN' => '5',
'DAGB' => 20,
'REK' => 20032,
'TEGREK' => '40',
'FACT' => 0,
'BTW' => 4,
'BEDRBOEK' => 123.45,
'DAT' => '08-05-2018',
'OPM' => 'Anand testing from wsdl',
'BEDRBTW' => 21,
'FACT' => 0,
'OMSCHR' => 'Testing from wsdl api',
'BOEKSTUK' => 2018075
],
'DIGDOS' => [
'FILE' => $base64_encode
]
];
$journaalpost = ArrayToXml::convert($array, 'NewDataSet');//convert array to xml string
$create = new \mysdk\ImuisSDK\ServiceType\Create($options);
if ($create->CreateJournaalpost(new \mysdk\ImuisSDK\StructType\CreateJournaalpost($partnerKey, $omgevingscode, $sessionid, $journaalpost)) !== false) {
$jsonResponse = $create->getResult();
} else {
$jsonResponse = $create->getLastError();
}
return $jsonResponse;
}
?>
I think the problem is that WsdlToPhp has constructed client code which is sending the PDF entity as a String, when it needs to be a byte[].
So I think the problem may be in code that is not shown here.
Can you take a look at the code generated by WsdlToPhp and see if you have any flexibility in how the $journaalpost is serialized to see if you can fix in there?
// Convert the Base64 string back to text.
var byteString = atob(data.reportBase64Bytes);
// Convert that text into a byte array.
var ab = new ArrayBuffer(byteString.length);
var ia = new Uint8Array(ab);
for (var i = 0; i < byteString.length; i++) {
ia[i] = byteString.charCodeAt(i);
}
// Blob for saving.
var blob = new Blob([ia], { type: "application/pdf" });
// Tell the browser to save as report.pdf.
saveAs(blob, "report.pdf");
// Alternatively, you could redirect to the blob to open it in the browser.
//document.location.href = window.URL.createObjectURL(blob);
There is a "bug" in the IMUIS software so it cant be possible to link a pdf file from php. Its may be done by Dotnet because its native language and the entire system built by it. Thanks to all of my SO friends for your efforts to helps me to find the issue, i have confirmed this information after call support. So in the future no one get stuck (afterall maybe end of 2018) :)

Laravel: Count number of uploads and return those

Using this lib uploading works great. I have number of objects in an excel and I go through them and do whatever I desire.
The question is while uploading the excel I am ought to check whether a particular object already exists, if so increment the $rejected variable otherwise create and increment the $uploaded variable. As a result I would like to return the results: how many uploaded and how many rejected? Whats the best way to do as such? It is obvious I can't access those variables inside the function. What's the best practice here?
public function uploadUsingFile($file)
{
$rejected = 0;
$uploaded = 0;
Excel::load($file, function ($reader) {
foreach ($reader->toArray() as $row)
{
$plateAlreadyExist = Plate::where('serial_number', $row['plate_serial_number'])->exists();
if ($plateAlreadyExist) {
$rejected += 1;continue;
}
$supplier = Supplier::firstOrCreate(['name' => $row['supplier_name']]);
$statusName = EquipmentStatusCode::firstOrCreate(['name' => $row['status_name']]);
$plateType = PlateType::firstOrCreate(['name' => $row['plate_type_name']]);
$process = Process::firstOrCreate(['name' => $row['process_name']]);
$project = Project::firstOrCreate(['name' => $row['project_name']]);
$plateQuality = PlateQuality::firstOrCreate(['name' => $row['plate_quality']]);
$wafer = Wafer::firstOrCreate(['serial_number' => $row['wafer_serial_number']]);
$data = [
'serial_number' => $row['plate_serial_number'],
'crc_code' => $row['crc_code'],
'supplier_id' => $supplier['id'],
'equipment_status_code_id' => $statusName['id'],
'plate_type_id' => $plateType['id'],
'process_id' => $process['id'],
'project_id' => $project['id'],
'plate_quality_id' => $plateQuality['id'],
'wafer_id' => $wafer['id'],
'created_by' => Auth::user()->id,
];
if($data)
{
Plate::create($data);
$uploaded += 1;
}
}
});
return [ 'uploaded' => $uploaded, 'rejected' => $rejected ];
}
You can pass a reference to the variables into the closure by using the use keyword:
...
Excel::load($file, function ($reader) use(&$rejected, &$uploaded){
...
}
Anonymous Functions

Categories