Does not display the result of parsing - php

Good afternoon, please help me. At me when parsing the result of parsing is not displayed.
link my php file https://dropmefiles.com/cv4Q2
Please correct where I was wrong. Or help to rewrite a little code so that it displays the result of the parser.
Already tried all the options, it does not work in any way. My knowledge here is not enough.
1 file
part 1
function getForecastXML($cid='579432') {
$cid = "579432";
$hoffset = "4";
$appid= "d86ad74d22ce9cc528d8baee65acd408";
$lang= "ru";
$days = array();
$xml = #file_get_contents("http://api.openweathermap.org/data/2.5/forecast?id=$cid&mode=xml&appid=$appid&lang=$lang&type=like");
if ($xml===false) { return;} else {
$xml = simplexml_load_string($xml);
$cityname = (string)$xml->location->name;
$weekdays[0] = "Воскресенье";
$weekdays[1] = "Понедельник";
$weekdays[2] = "Вторник";
$weekdays[3] = "Среда";
$weekdays[4] = "Четверг";
$weekdays[5] = "Пятница";
$weekdays[6] = "Суббота";
if (count($xml->forecast->time)>0){
foreach ($xml->forecast->time as $fpart) {
$forecast = array();
$attr = $fpart->attributes();
$forecast['t']['min'] = (string)round(($fpart->temperature->attributes()->min)-273,15,PHP_ROUND_HALF_UP);
$forecast['t']['min'] = $forecast['t']['min'] > 0 ? "+".$forecast['t']['min'] : $forecast['t']['min'];
$forecast['t']['max'] = (string)round(($fpart->temperature->attributes()->max)-273,15,PHP_ROUND_HALF_UP);
$forecast['t']['max'] = $forecast['t']['max'] > 0 ? "+".$forecast['t']['max'] : $forecast['t']['max'];
$forecast['p']['min'] = (string)round($fpart->pressure->attributes()->value,0,PHP_ROUND_HALF_UP);
// $forecast['p']['max'] = (string)$fpart->PRESSURE->attributes()->max;
$forecast['w']['min'] = (string)round($fpart->windSpeed->attributes()->mps,0,PHP_ROUND_HALF_UP);
//$forecast['w']['max'] = (string)$fpart->WIND->attributes()->max;
//$forecast['w']['rumb'] = (string)$fpart->WIND->attributes()->direction;
$forecast['h']['min'] = (string)$fpart->humidity->attributes()->value;
//$forecast['h']['max'] = (string)$fpart->RELWET->attributes()->max;
$forecast['symb'] = (string)$fpart->symbol->attributes()->name;
$forecast['pict'] = (string)$fpart->symbol->attributes()->var;
$date = date('c',strtotime($hoffset.' hours',strtotime($attr['from'])));
$hour = date('H',strtotime($date));
$forecast['timestamp'] =strtotime($date);
$date = strtotime($date);
$dayofweek = date('w',$date);
$date = $weekdays[$dayofweek]." ".date('d.m',$date);
if ($forecast['timestamp'] > time()){
$days[$date][$hour] = $forecast;
}
}
} else {$days=array();}
}
//return array($cityname,$days);
return [$cityname => $days];
//echo [$cityname => $days];
}
part 2
$outputData = array();
if (count($this->forecast) > 0) {
foreach ($this->forecast as $date => $daypart) {
$outputData[] = $date;
foreach ($daypart as $dp => $data) {
$outputData[] = str_pad($dp, 2, '0', STR_PAD_LEFT);
$outputData[] = $data['symb'];
$outputData[] = $data['t']['min'];
$outputData[] = $data['t']['max'];
if (($data['p']['min']) > 0) {
$outputData[] = "Давление " . round($data['p']['min'] * 0.75006375541921) . "мм. рт. ст.";
}
}
}
} else {
$outputData[] = "В данный момент информация о погоде отсутствует";
}
echo implode(' ', $outputData);

Related

Datatables very slow load on Codeigniter

I have to get data from fingerprint machine. Everything in my code run and works, but if I show all employee data, it loads very slow.
I have create datatables by codeigniter and ajax call to view. My code like below
// Datatables Variables
$draw = intval($this->input->get("draw"));
$start = intval($this->input->get("start"));
$length = intval($this->input->get("length"));
$year = $this->input->post("year");
$month = $this->input->post("month");
$dept = $this->input->post("dept");
$where = $year.'-'.$month.'-';
$shifts = $this->m_general->get_data('tb_shift')->result();
$rows = $this->m_employee->attendance($where)->result_array();
if($dept=='5'){
$pin_emp = $this->m_general->get_data('tb_employee')->result();
}else{
$pin_emp = $this->m_general->check_data('tb_employee',array('emp_dept'=>$dept))->result();
}
$loc_machine= $this->m_general->get_data('tb_pkm')->result();
$roaster = $this->m_employee->list_schedule_emp($where)->result_array();
$holiday = $this->m_general->get_data('tb_holiday')->result();
$total_days = tglakhir($year,$month);
$dates = array();
$people = array();
$data = array();
foreach ($rows as $row) {
if (empty($row['date']) || empty($row['pin'])) {
continue; // no date or sn, nothing to print for this row...
}
// in array assures unique values
if (!in_array($row['date'], $dates)) {
$dates[] = $row['date'];
}
// this may seem convoluted, take your time to understand
$people[$row['date']][$row['pin']] = $row;
$array_emp[$row['date']][$row['pin']][] = $row;
}
foreach ($roaster as $rs) {
if (empty($rs['date']) || empty($rs['id_nip'])) {
continue; // no date or sn, nothing to print for this row...
}
// this may seem convoluted, take your time to understand
$get_rs[$rs['date']][$rs['id_nip']] = $rs;
$dt_rs[$rs['date']][$rs['id_nip']][] = $rs;
}
foreach($pin_emp AS $q){
$array_pin[]=$q->emp_pin;
$details[$q->emp_pin] = $q;
}
foreach($holiday AS $hday){
$get_hday[$hday->date_holiday] = $hday;
}
foreach($loc_machine AS $list_machine){
$lm[$list_machine->id_machine] = $list_machine;
}
for($m=1; $m <= $total_days; $m++){
if($m<10){
$m = '0'.$m;
}else{
$m = $m;
}
$date[]=$m;
}
foreach($shifts AS $shift_e){
$array_shift[$shift_e->id_shift] = $shift_e;
$ar_shift[]=$shift_e->id_shift;
}
foreach ($array_pin AS $id){
$name = $details[$id]->emp_name;
$shift = $details[$id]->emp_shift;
$id_machine = $details[$id]->emp_reg_sn;
if(isset($lm[$id_machine])){
$loc_machine= $lm[$id_machine]->pkm_name;
}
$date_range = array();
foreach($date AS $date_col){
$day = date('D', strtotime($year.'-'.$month.'-'.$date_col));
$today = date('Y-m-d');
$full_day = $year.'-'.$month.'-'.$date_col;
$s_in = '';
$s_out = '';
$time_in = '';
$time_out = '';
$t_in = '';
$t_out = '';
$finger_tap = '';
$diff_in = '';
$diff_out = '';
$diff = null;
$diff2 = null;
$late = '00:00:00';
$r = $date_col;
$title = '';
$date_holiday= '';
if (ISSET($get_hday[$full_day])==TRUE) {
$date_holiday = $get_hday[$full_day]->date_holiday;
$title = $get_hday[$full_day]->note_holiday;
}
foreach ($dates as $key) {
$shift_detail= $array_shift[$shift]->code_shift;
if(isset($get_rs[$full_day][$id]['id_shift_emp']) && $get_rs[$full_day][$id]['id_shift_emp']!=''){
$shift = $get_rs[$full_day][$id]['id_shift_emp'];
$shift_detail = $array_shift[$shift]->code_shift;
}
if (isset($people[$key][$id]['date']) && $people[$key][$id]['date'] == $key) {
foreach ($array_emp[$key][$id] AS $dtl){
if(isset($get_rs[$key][$id]['id_shift_emp']) && $get_rs[$key][$id]['id_shift_emp']!=''){
$shift = $get_rs[$key][$id]['id_shift_emp'];
}
$shift = $dtl['emp_shift'];
$date_time = $dtl['date_time'];
if(($shift==5)OR($shift==7)OR($shift==9)OR($shift==11)OR($shift==12)OR($shift==14)){
$r = $date_col+1;
}
if(substr($key,8,2)==$date_col){
$status_code= $dtl['status_code'];
$status_note= $dtl['att_status'];
$first_in = strtotime($year.'-'.$month.'-'.$date_col.' '.$array_shift[$shift]->first_check);
$last_out = strtotime($year.'-'.$month.'-'.$r.' '.$array_shift[$shift]->last_check);
$shift_in = $array_shift[$shift]->in_shift;
$shift_out = $array_shift[$shift]->out_shift;
$s_in = strtotime($year.'-'.$month.'-'.$day.' '.$shift_in);
$s_out = strtotime($year.'-'.$month.'-'.$day.' '.$shift_out);
$finger_tap = strtotime($date_time);
$shift_detail= $array_shift[$shift]->code_shift;
foreach($ar_shift AS $id_shift){
if ($shift==$id_shift) {
$currdiff = abs($finger_tap - $first_in);
if (is_null($diff) || $currdiff < $diff) {
$diff = $currdiff;
$time_in = date('H:i:s',strtotime($date_time));
$t_in = strtotime($date_time);
if(($t_in-$s_in)>0){
$diff_in = gmdate('H:i:s',$t_in-$s_in);
}else{
$diff_in = $late;
}
}
$currdiff2 = abs($finger_tap - $last_out);
if (is_null($diff2) || $currdiff2 < $diff2) {
$diff2 = $currdiff2;
$time_out = date('H:i:s',strtotime($date_time));
$t_out = strtotime($date_time);
if(($t_out-$s_out)>0){
$diff_out = $late;
}else{
$diff_out= gmdate('H:i:s',$s_out-$t_out);
}
}
}
}
}
if(($shift==5)OR($shift==7)OR($shift==9)OR($shift==11)OR($shift==12)OR($shift==14)){
if ($day==$r) {
$shift_out = $array_shift[$shift]->out_shift;
$s_out = strtotime($year.'-'.$month.'-'.$r.' '.$shift_out);
$finger_tap = strtotime($date_time);
foreach($ar_shift AS $id_shift){
if ($shift==$id_shift) {
$currdiff2 = abs($finger_tap - $last_out);
if (is_null($diff2) || $currdiff2 < $diff2) {
$diff2 = $currdiff2;
$time_out = date('H:i:s',strtotime($date_time));
$t_out = strtotime($date_time);
if(($t_out-$s_out)>0){
$diff_out = $late;
}else{
$diff_out= gmdate('H:i:s',$s_out-$t_out);
}
}
}
}
}
}
$status = '<i class="material-icons col-green">check_box_outline_blank</i>'.$shift_detail.'';
if($year.'-'.$month.'-'.$date_col < $today){
$status = '<i class="material-icons col-red">fiber_manual_record</i>'.$shift_detail.'';
}
if(($day == 'Sun') OR ($day == 'Sat')){
$status='<a href="javascript:change_status_att(\''.$id.'\',\''.$name.'\',\''.$full_day.'\')" class="btn btn-md bg-red waves-effect" data-toggle="tooltip" data-placement="top" title="Libur">off</button>';
}
if($date_holiday == $full_day){
$status = '<i class="material-icons col-red">today</i>OFF';
}
if($time_in!=''){
if($time_in==$time_out){
$status = '<i class="material-icons col-red">brightness_6</i>'.$shift_detail.'';
}
if ($status_code!='') {
$status = '<i class="material-icons col-orange">sim_card_alert</i>'.$shift_detail.'';
}
}
if($time_in!=$time_out){
$status = '<i class="material-icons col-green">check_box</i>'.$shift_detail.'';
}
if($time_in=='00:00:00'){
$status = '<i class="material-icons col-orange">sim_card_alert</i>'.$shift_detail.'';
}
}
}
}
$date_range[] = $status;
}
$first = array(
''.$id.'',
$name,
$loc_machine
);
$data[] = array_merge($first,$date_range);
}
$output = array(
"draw" => $draw,
"recordsTotal" => '',
"recordsFiltered" =>'' ,
"data" => $data
);
$this->output->set_content_type('application/json')->set_output(json_encode($output));
}
This code runs and works, but need about 10 second for load.
Can somebody help Me what I have to do to be fast this load?
UPDATE
after I analysis my code, the slow load data because datatables say "data was truncated". But when I load on small data(filtered), It was fine.
problem still same when I get all data from database.
To make it faster, you first need to know what is slow. To do that, you need to use debugging tools, like this one and timestamps.
Then, once you get logs with the duration of your processes, you can analyze it to know which part of your code is slow.
Then, try to optimize it. And if you can’t, edit your question to focus on the slow part or post a new one.

PHP Error 500 Internal Server Error in Codeigniter 3 When large Transaction

I have a problem when execute large transaction in Codeigniter 3.
I create transaction for migrating old data like below:
// Controller
public function migrate_document_get()
{
$this->benchmark->mark('code_start');
$data = $this->Delivery_order_model->read_data_class_from_stock();
foreach ($data as $obj) {
$parameters = $this->Delivery_order_model->read_data_for_do($obj->class_no);
$this->Delivery_order_model->create_data($parameters);
}
$this->benchmark->mark('code_end');
$data['message'] = "Finish migrate document DO";
$data['execution_time'] = round($this->benchmark->elapsed_time('code_start', 'code_end')) . " seconds";
$this->response($data, REST_Controller::HTTP_OK);
}
// Model
function create_data($data)
{
$error = array();
$affected_rows = 0;
$this->mysql->trans_start();
foreach ($data as $row) {
$sql_insert_product = "";
$class_no = $row['class_no'];
$article_vendor = $row['article_vendor'];
$style = $row['style'];
$sku_promo = $row['sku_promo'];
$retail = $row['retail'];
$unique_id = $this->generate_unique_id($class_no, $article_vendor, $style, $sku_promo, $retail);
$sku_no = $class_no . $unique_id . $style . $sku_promo . $retail;
$article_no = $class_no . $style . $sku_promo . $retail;
$res_field = $unique_id . $style . $sku_promo;
$format = array();
$format['dept_no'] = $row['dept_no'];
$format['class_no'] = $class_no;
$format['sku_no'] = $sku_no;
if (!empty($row['ref_no'])) {
$format['ref_no'] = $row['ref_no'];
}
$format['article_vendor'] = $article_vendor;
$format['article_no'] = $article_no;
$format['res_field'] = $res_field;
$format['style'] = $style;
$format['category_no'] = $row['category_no'];
$format['size_no'] = $row['size_no'];
$format['color_no'] = $row['color_no'];
$format['material_no'] = $row['material_no'];
$format['unique_id'] = $unique_id;
$format['sku_promo'] = $sku_promo;
if (!empty($row['exp_promo']) and $row['sku_promo'] != "00") {
$format['exp_promo'] = date('Y-m-d', strtotime(str_replace('/', '-', str_replace("'", "", $row['exp_promo']))));
}
$format['season_code'] = date('ym');
$format['retail'] = $retail;
$format['tag_type'] = $row['tag_type'];
if (!empty($row['image'])) {
$format['image'] = $row['image'];
}
$format['time_create'] = date('Y-m-d H:i:s');
$sql_insert_product = $this->mysql->insert_ignore_string("msr_product", $format);
// Transaction 1 -> INSERT msr_product
$this->mysql->query($sql_insert_product);
$sql_insert_do = "";
$format_doc = "DO" . $class_no . date('Ymd');
$do_id = $this->generate_do_id($format_doc);
$doc_no = $format_doc . $do_id;
$store_no = $row['store_no'];
// INSERT msr_do
$format_insert = array();
$format_insert['do_no'] = $doc_no;
$format_insert['store_no'] = $store_no;
$format_insert['sku_no'] = $sku_no;
$format_insert['do_date1'] = date('Y-m-d', strtotime(date('Ymd')));
$format_insert['do_date2'] = date('Y-m-d', strtotime('60 day', strtotime(date('Ymd'))));
$format_insert['do_status'] = 1;
$format_insert['user_input'] = $row['nik'];
$format_insert['ts_input'] = date('Y-m-d H:i:s');
$format_insert['status_item'] = 0;
$format_insert['qty_store'] = $row['qty'];
$format_update['qty_store'] = "qty_store + " . $row['qty'];
$sql_insert_do = $this->mysql->insert_on_duplicate_update_string("msr_do", $format_insert, $format_update, true, false);
// Transaction 2 -> INSERT msr_do
$this->mysql->query($sql_insert_do);
$affected_rows += $this->mysql->affected_rows();
}
$this->mysql->trans_complete();
if ($this->mysql->trans_status() === FALSE) {
$error = $this->mysql->error();
$error['sql_product'] = $sql_insert_product;
$error['sql_do'] = $sql_insert_do;
}
return $this->commonutil->format_output($affected_rows, $error);
}
When I execute method above in loop,
I facing an issue with error 500 internal server error.
but when I execute method like below one by one, not in the loop it's running normally.
// Controller
public function create_post()
{
$this->benchmark->mark('code_start');
$parameters = $this->post();
if (!empty($parameters)) {
$validate_param = $this->validate_parameter_create($parameters[0]);
if ($validate_param->run() == TRUE) {
$save = $this->Delivery_order_model->create_data($parameters);
if (!empty($save) and $save['total_affected'] > 0) {
$this->benchmark->mark('code_end');
$output['status'] = REST_Controller::HTTP_OK;
$output['error'] = false;
$output['message'] = "Success create delivery order list.";
$output['execution_time'] = $this->benchmark->elapsed_time('code_start', 'code_end') . " seconds.";
$this->response($output, REST_Controller::HTTP_OK);
} else {
$this->benchmark->mark('code_end');
$output['status'] = REST_Controller::HTTP_NOT_MODIFIED;
$output['error'] = true;
$output['error_detail'] = $save['error'];
$output['message'] = "Failed create delivery order list!";
$output['execution_time'] = $this->benchmark->elapsed_time('code_start', 'code_end') . " seconds.";
$this->response($output, REST_Controller::HTTP_NOT_MODIFIED);
}
} else {
$this->benchmark->mark('code_end');
$output['status'] = REST_Controller::HTTP_UNPROCESSABLE_ENTITY;
$output['error'] = true;
$output['error_detail'] = $validate_param->error_array();
$output['message'] = "Required JSON Array! [{.....}]";
$output['execution_time'] = $this->benchmark->elapsed_time('code_start', 'code_end') . " seconds.";
$this->response($output, REST_Controller::HTTP_UNPROCESSABLE_ENTITY);
}
} else {
$this->benchmark->mark('code_end');
$output['status'] = REST_Controller::HTTP_UNPROCESSABLE_ENTITY;
$output['error'] = true;
$output['message'] = "Required parameters!";
$output['execution_time'] = $this->benchmark->elapsed_time('code_start', 'code_end') . " seconds.";
$this->response($output, REST_Controller::HTTP_UNPROCESSABLE_ENTITY);
}
}
// Model
function create_data($data)
{
$error = array();
$affected_rows = 0;
$this->mysql->trans_start();
foreach ($data as $row) {
$sql_insert_product = "";
$class_no = $row['class_no'];
$article_vendor = $row['article_vendor'];
$style = $row['style'];
$sku_promo = $row['sku_promo'];
$retail = $row['retail'];
$unique_id = $this->generate_unique_id($class_no, $article_vendor, $style, $sku_promo, $retail);
$sku_no = $class_no . $unique_id . $style . $sku_promo . $retail;
$article_no = $class_no . $style . $sku_promo . $retail;
$res_field = $unique_id . $style . $sku_promo;
$format = array();
$format['dept_no'] = $row['dept_no'];
$format['class_no'] = $class_no;
$format['sku_no'] = $sku_no;
if (!empty($row['ref_no'])) {
$format['ref_no'] = $row['ref_no'];
}
$format['article_vendor'] = $article_vendor;
$format['article_no'] = $article_no;
$format['res_field'] = $res_field;
$format['style'] = $style;
$format['category_no'] = $row['category_no'];
$format['size_no'] = $row['size_no'];
$format['color_no'] = $row['color_no'];
$format['material_no'] = $row['material_no'];
$format['unique_id'] = $unique_id;
$format['sku_promo'] = $sku_promo;
if (!empty($row['exp_promo']) and $row['sku_promo'] != "00") {
$format['exp_promo'] = date('Y-m-d', strtotime(str_replace('/', '-', str_replace("'", "", $row['exp_promo']))));
}
$format['season_code'] = date('ym');
$format['retail'] = $retail;
$format['tag_type'] = $row['tag_type'];
if (!empty($row['image'])) {
$format['image'] = $row['image'];
}
$format['time_create'] = date('Y-m-d H:i:s');
$sql_insert_product = $this->mysql->insert_ignore_string("msr_product", $format);
// Transaction 1 -> INSERT msr_product
$this->mysql->query($sql_insert_product);
$sql_insert_do = "";
$format_doc = "DO" . $class_no . date('Ymd');
$do_id = $this->generate_do_id($format_doc);
$doc_no = $format_doc . $do_id;
$store_no = $row['store_no'];
// INSERT msr_do
$format_insert = array();
$format_insert['do_no'] = $doc_no;
$format_insert['store_no'] = $store_no;
$format_insert['sku_no'] = $sku_no;
$format_insert['do_date1'] = date('Y-m-d', strtotime(date('Ymd')));
$format_insert['do_date2'] = date('Y-m-d', strtotime('60 day', strtotime(date('Ymd'))));
$format_insert['do_status'] = 1;
$format_insert['user_input'] = $row['nik'];
$format_insert['ts_input'] = date('Y-m-d H:i:s');
$format_insert['status_item'] = 0;
$format_insert['qty_store'] = $row['qty'];
$format_update['qty_store'] = "qty_store + " . $row['qty'];
$sql_insert_do = $this->mysql->insert_on_duplicate_update_string("msr_do", $format_insert, $format_update, true, false);
// Transaction 2 -> INSERT msr_do
$this->mysql->query($sql_insert_do);
$affected_rows += $this->mysql->affected_rows();
}
$this->mysql->trans_complete();
if ($this->mysql->trans_status() === FALSE) {
$error = $this->mysql->error();
$error['sql_product'] = $sql_insert_product;
$error['sql_do'] = $sql_insert_do;
}
return $this->commonutil->format_output($affected_rows, $error);
}
I already resizing on DB temp space
and I already check the method it's running normally
what's wrong with that, please give me some advice.

How to insert in to two tables from an online from?

Is it possible to insert in to two tables at once? I need to insert some data in to a table (students) and then based on the primary key insert in to another (enrollments). Is this possible?
The enrollments table however pulls other primary key from another table called schools (id).
public function add()
{
if(isset($_POST['submit'])) {
$this->student_validation();
if($this->form_validation->run() === TRUE) {
$data = $this->_get_posted_student_data();
$insert_id = $this->student->insert('students', $data);
if($insert_id) {
$this->__insert_enrollment($insert_id);
success($this->lang->line('insert_success'));
redirect('web/index/' . $data['front_school_id']);
} else {
error($this->lang->line('insert_failed'));
redirect('web/admission');
}
} else {
$this->data['post'] = $_POST;
}
}
$this->data['schools'] = $this->schools;
$this->data['add'] = TRUE;
$this->layout->title($this->lang->line('add') . ' ' . $this->lang->line('student') . ' | ' . SMS);
$this->layout->view('web/index', $this->data);
}
private function __insert_enrollment($insert_id)
{
$data = array();
$school = $this->student->get_school_by_id($this->input->post('front_school_id'));
$data['student_id'] = $insert_id;
$data['school_id'] = $this->input->post('front_school_id');
//$data['class_id'] = $this->input->post('class_id');
//$data['section_id'] = $this->input->post('section_id');
$data['academic_year_id'] = $school->academic_year_id;
//$data['roll_no'] = $this->input->post('roll_no');
$data['created_at'] = date('Y-m-d H:i:s');
//$data['created_by'] = logged_in_user_id();
$data['status'] = 1;
$this->db->insert('enrollments', $data);
}
private function _get_posted_student_data()
{
$items = array();
$school_id = $this->session->userdata('front_school_id');
$items[] = 'first_name';
$items[] = 'middle_name';
$items[] = 'last_name';
$items[] = 'gender';
$items[] = 'religion';
$items[] = 'dobpin';
$items[] = 'address';
$items[] = 'immunization_update';
$items[] = 'nationality';
$items[] = 'valid_permit';
$items[] = 'relation_father';
$items[] = 'father_name';
$items[] = 'father_phone';
$items[] = 'father_email';
$items[] = 'father_address';
$items[] = 'relation_mother';
$items[] = 'mother_name';
$items[] = 'mother_phone';
$items[] = 'mother_email';
$items[] = 'mother_address';
$items[] = 'other_sibling';
$items[] = 'name_sibling';
$items[] = 'class_sibling';
$items[] = 'name';
$items[] = 'relation';
$items[] = 'child';
$items[] = 'application_name';
$data = elements($items, $_POST);
$data['dob'] = date('Y-m-d', strtotime($this->input->post('dob')));
$data['admission_date'] = date('Y-m-d', strtotime($this->input->post('admission_date')));
$data['age'] = floor((time() - strtotime($data['dob'])) / 31556926);
$data['modified_at'] = date('Y-m-d H:i:s');
//$data['modified_by'] = logged_in_user_id();
$data['created_at'] = date('Y-m-d H:i:s');
//$data['created_by'] = logged_in_user_id();
$data['status'] = 1;
// create user
//$data['user_id'] = $this->student->create_user();
if($_FILES['birth_certificate']['name']) {
$data['birth_certificate'] = $this->_upload_birth_certificate();
}
if($_FILES['bill']['name']) {
$data['bill'] = $this->_upload_bill();
}
if($_FILES['immunization']['name']) {
$data['immunization'] = $this->_upload_immunization();
}
if($_FILES['photo']['name']) {
$data['photo'] = $this->_upload_photo();
}
return $data;
}
You need $this->db->insert_id() to get last inserted id which will get from this.
$this->db->insert('students', $data);
$insert_id = $this->db->insert_id();
if(!empty($insert_id)) {
$this->__insert_enrollment($insert_id);
success($this->lang->line('insert_success'));
redirect('web/index/' . $data['front_school_id']);
} else {
error($this->lang->line('insert_failed'));
redirect('web/admission');
}

array_multisort how to mount with foreach

I need to mount an array_multisort with the values from one array.
I tryied to mount a string concated and call on the array_multidimensional like here:
function ordenar_matriz_ultima_posicion_por_distancia($matriz_up,$m_vehiculo_distancias){
$total_vehiculos=count($matriz_up[id_vehiculo]);
//resetear las keys de vehiculos para coger bien los kms y asignarlos
$a_vehiculo_distancia = array_values($m_vehiculo_distancias);
$ordenar = array();
foreach ($a_vehiculo_distancia as $key) {
$ordenar[] = $key;
}
sort($m_vehiculo_distancias);
$string= "";
$ultim_key = end(array_keys($matriz_up));
foreach ($matriz_up as $key => $valor) {
if ($key != $ultim_key) $string.= $matriz_up[$key].',';
else $string.= $matriz_up[$key];
$aaa = '$matriz_up[$key]';
}
echo $string;
echo "<br>";
array_multisort($ordenar, SORT_ASC, $string);
for($i=0;$i<$total_vehiculos;$i++){
$matriz_up['cercanos'][$i] = $m_vehiculo_distancias[$i];
echo $matriz_up['id_vehiculo'][$i]."<br>";
echo $matriz_up['fecha_gps'][$i]."<br>";
echo $matriz_up['id_tipo_posicion'][$i]."<br>";
echo $matriz_up['cercanos'][$i]."<br>";
echo $matriz_up['vaina'][$i]."<br>";
echo "------------<br>";
}
return $matriz_up;
}
$matriz_up['id_vehiculo'][0] = 9;
$matriz_up['fecha_gps'][0] = '2014';
$matriz_up['id_tipo_posicion'][0] = 11111;
$matriz_up['cercanos'][0] = 0;
$matriz_up['vaina'][0] = 12345;
$matriz_up['id_vehiculo'][1] = 3;
$matriz_up['fecha_gps'][1] = '2015';
$matriz_up['id_tipo_posicion'][1] = 22222;
$matriz_up['cercanos'][1] = 0;
$matriz_up['vaina'][1] = 5555;
$matriz_up['id_vehiculo'][2] = 1;
$matriz_up['fecha_gps'][2] = '2016';
$matriz_up['id_tipo_posicion'][2] = 33333;
$matriz_up['cercanos'][2] = 0;
$matriz_up['vaina'][2] = 988;
$matriz_up['id_vehiculo'][3] = 4;
$matriz_up['fecha_gps'][3] = '2017';
$matriz_up['id_tipo_posicion'][3] = 44444;
$matriz_up['cercanos'][3] = 0;
$matriz_up['vaina'][3] = 777;
$m_vehiculo_distancias[9] = 345;
$m_vehiculo_distancias[3] = 712;
$m_vehiculo_distancias[1] = 10;
$m_vehiculo_distancias[4] = 35;
ordenar_matriz_ultima_posicion_por_distancia($matriz_up,$m_vehiculo_distancias);
With this array_multisort works, but i need to take all the key without put manually..
array_multisort($ordenar, SORT_ASC, $matriz_up['id_vehiculo'], $matriz_up['fecha_gps'], $matriz_up['id_tipo_posicion'], $matriz_up['vaina'] );
Try this code:
<?php
$matriz_up = $m_vehiculo_distancias = array();
$matriz_up['id_vehiculo'][0] = 9;
$matriz_up['fecha_gps'][0] = '2014';
$matriz_up['id_tipo_posicion'][0] = 11111;
$matriz_up['cercanos'][0] = 0;
$matriz_up['vaina'][0] = 12345;
$matriz_up['id_vehiculo'][1] = 3;
$matriz_up['fecha_gps'][1] = '2015';
$matriz_up['id_tipo_posicion'][1] = 22222;
$matriz_up['cercanos'][1] = 0;
$matriz_up['vaina'][1] = 5555;
$matriz_up['id_vehiculo'][2] = 1;
$matriz_up['fecha_gps'][2] = '2016';
$matriz_up['id_tipo_posicion'][2] = 33333;
$matriz_up['cercanos'][2] = 0;
$matriz_up['vaina'][2] = 988;
$matriz_up['id_vehiculo'][3] = 4;
$matriz_up['fecha_gps'][3] = '2017';
$matriz_up['id_tipo_posicion'][3] = 44444;
$matriz_up['cercanos'][3] = 0;
$matriz_up['vaina'][3] = 777;
$m_vehiculo_distancias[9] = 345;
$m_vehiculo_distancias[3] = 712;
$m_vehiculo_distancias[1] = 10;
$m_vehiculo_distancias[4] = 35;
function sortArray($arrayToSortParam, $orderArray)
{
$result = array();
$arrayToSort = $arrayToSortParam;
$keys = array_keys($arrayToSort);
asort($orderArray, true);
$newSort = $cercanos = array();
foreach($orderArray as $key => $value)
{
$newSort[] = array_keys($arrayToSort['id_vehiculo'], $key)[0];
$cercanos[] = $orderArray[$key];
}
foreach($keys as $keyName)
{
uksort($arrayToSort[$keyName], function($key1, $key2) use ($newSort) {
return (array_search($key1, $newSort) > array_search($key2, $newSort));
});
}
$arrayToSort['cercanos'] = $cercanos;
//reset indexes
foreach($keys as $keyName)
{
$arrayToSort[$keyName] = array_values($arrayToSort[$keyName]);
}
return $arrayToSort;
}
echo '<pre>';
//print_r($matriz_up);
//print_r($m_vehiculo_distancias);
print_r(sortArray($matriz_up, $m_vehiculo_distancias)); //this is result
Working fiddle: CLICK!

Previous/next button in PHP

I´m pretty much entirely new to PHP, so please bear with me.
I´m trying to build a website running on a cms called Core. I'm trying to make it so that the previous/next buttons cycle through tags rather than entries. Tags are stored in a database as core_tags. Each tag has it own tag_id, which is a number. I've tried changing the excisting code for thep previous/next buttons, but it keeps giving me 'Warning: mysql_fetch_array() expects parameter 1 to be resource, null given in /home/core/functions/get_entry.php on line 50'.'
Any help would be greatly appreciated.
Get_entry.php:
<?php
$b = $_SERVER['REQUEST_URI'];
if($entry) {
$b = substr($b,0,strrpos($b,"/")) . "/core/";
$id = $entry;
$isPerma = true;
} else {
$b = substr($b,0,mb_strrpos($b,"/core/")+6);
$id = $_REQUEST["id"];
}
$root = $_SERVER['DOCUMENT_ROOT'] . $b;
$http = "http://" . $_SERVER['HTTP_HOST'] . substr($b,0,strlen($b)-5);
require_once($root . "user/configuration.php");
require_once($root . "themes/".$theme."/configuration.php");
require_once($root . "functions/session.php");
if(is_numeric($id)) {
$type = "entry";
} else {
$type = "page";
}
$id = secure($id);
if($type == "page") {
$data = mysql_query("SELECT p.* FROM core_pages p WHERE p.page_title = \"$id\"");
$page_clicks = 0;
while($p = mysql_fetch_array($data)) {
$url = $p["page_url"];
$path = $root . "user/pages/" . $url;
$page_clicks = $p['hits']+1;
require($path);
}
mysql_query("UPDATE core_pages p SET
p.hits = $page_clicks
WHERE p.page_title = $id");
}
if($type == "entry") {
// queries the dbase
$data_tags = mysql_query("SELECT entry_id,entry_title FROM core_entries WHERE entry_show = 1 ORDER BY entry_position DESC") or die(mysql_error());
$navArr=array();
while($tmparray = mysql_fetch_array($data_entries,MYSQL_ASSOC)){
array_push($navArr,$tmparray['entry_id']);
}
function array_next_previous($array, $value) {
$index = array_search($value,$array);
//if user clicked to view the very first entry
if($value == reset($array)){
$return['prev'] = end($array);
$return['next'] = $array[$index + 1];
//if user clicked to view the very last entry
}else if($value == end($array)){
$return['prev'] = $array[$index - 1];
reset($array);
$return['next'] = current($array);
}else{
$return['next'] = $array[$index + 1];
$return['prev'] = $array[$index - 1];
}
return $return;
}
$data = mysql_query("SELECT e.* FROM core_entries e WHERE e.entry_id = $id AND e.entry_show = 1");
$entry_clicks = 0;
if(#mysql_num_rows($data) < 1) {
die("Invalid id, no entry to be shown");
}
while($e = mysql_fetch_array($data)) {
$nextPrevProject = array_next_previous($navArr,$id);
$entry_id = $e['entry_id'];
$entry_title = $e['entry_title'];
// DATE
$t = $e["entry_date"];
$y = substr($t,0,4);
$m = substr($t,5,2);
$d = substr($t,8,2);
$entry_date = date($date_format,mktime(0,0,0,$m,$d,$y));
$entry_text = $e['entry_text'];
$entry_extra1 = $e['entry_extra1'];
$entry_extra2 = $e['entry_extra2'];
$entry_client = $e['entry_client'];
$entry_position = $e['entry_position'];
$entry_hits = $e['hits']+1;
$entry_new = $e['entry_new'];
if($entry_new == 1) {
$isNew = true;
} else {
$isNew = false;
}
if($nice_permalinks) {
$entry_perma = "$http".$entry_id;
} else {
$entry_perma = "$http"."?entry=$entry_id";
}
$data_e2t = #mysql_query("SELECT e2t.tag_id FROM core_entry2tag e2t WHERE e2t.entry_id = $entry_id");
$tag_str = "";
while($e2t = #mysql_fetch_array($data_e2t)) {
$tag_id = $e2t["tag_id"];
$data_tags = #mysql_query("SELECT t.tag_text FROM core_tags t WHERE t.tag_id = $tag_id");
while($t = #mysql_fetch_array($data_tags)) {
$tag_text = $t["tag_text"];
$tag_str = $tag_str . "<a class=\"tag-link\" name=\"tag".$tag_id."\" href=\"#tag-"._encode($tag_text)."\">".$tag_text."</a>".$separator_tags;
}
}
$entry_tags = substr($tag_str,0,strlen($tag_str)-strlen($separator_tags));
$layout_path = $root . "user/uploads/" . treat_string($entry_title) . "/layout.php";
if(is_file($layout_path) && (#filesize($layout_path) > 0)) {
require($layout_path);
} else {
require($theme_path . "parts/entry.php");
}
}
mysql_query("UPDATE core_entries e SET
e.hits = $entry_hits
WHERE e.entry_id = $id");
}
if($isPerma) {
echo "<a class=\"index-link\" href=\"$http\">back to index</a>";
}
?>
You have not defined $data_entries, before using it here:
while($tmparray = mysql_fetch_array($data_entries,MYSQL_ASSOC)){
array_push($navArr,$tmparray['entry_id']);
}
That is why you get the very descriptive error message.
Did you mean to use $data_tags?
Use: "SELECT p.* FROM core_pages p WHERE p.page_title = '".$id."'
Note: mysql_connect is not sql-injection save. If you use mysql_connect, change to PDO.
$data_entries is not defined on line 50, then mysql_fetch_array return an exception of null value given.
Try to change $tmparray = mysql_fetch_array($data_entries,MYSQL_ASSOC) to $tmparray = mysql_fetch_array($data_tags,MYSQL_ASSOC).
Hope this help!

Categories