API response slow - performance

My script works overall, but the API response is really slow.
This is what my code looks like:
<?php
error_reporting(E_ALL);
$config = include('config.php');
$predictions = include('predicton.php');
function fetchData($currency) {
$curl = curl_init();
curl_setopt_array($curl, array(
CURLOPT_RETURNTRANSFER => 1,
CURLOPT_URL => 'https://api.coinmarketcap.com/v1/ticker/'.$currency.'/?convert=EUR'
));
$response = curl_exec($curl);
$response = json_decode($response, true);
curl_close($curl);
return $response;
}
function convertData($currency) {
global $config;
$response = fetchData($currency);
$id = $response[0]['id'];
$name = $response[0]['name'];
$value = $response[0]['price_eur'];
$perc_change_h = $response[0]['percent_change_1h'];
$perc_change_d = $response[0]['percent_change_24h'];
$perc_change_w = $response[0]['percent_change_7d'];
$amount = $config[$currency]['amount'];
$starting_price = $config[$currency]['starting_price'];
$spend = $amount * $starting_price;
$total = $amount * $value;
$profit = $total - $spend;
return array(
'id' => $id,
'name' => $name,
'value' => round($value, 4),
'change_hour' => $perc_change_h,
'change_day' => $perc_change_d,
'change_week' => $perc_change_w,
'amount' => $amount,
'starting' => number_format($starting_price, 4),
'spend' => number_format($spend, 2),
'total' => number_format($total, 2),
'profit' => number_format($profit, 2)
);
}
function convertPrediction ($currency, $percentage) {
global $config, $predictions;
$amount = $config[$currency]['amount'];
$prediction = $predictions[$currency]['value'];
$value = $amount * $prediction / 100 * $percentage;
$value = round($value, 2);
return $value;
}
This is the site: http://bitcap.kazuto.de/
A sample api request: https://api.coinmarketcap.com/v1/ticker/stellar/?convert=EUR
The response itself is quick, but not when running in my code. It takes around 11-13 seconds to refresh, even though not much data is requested at all.
Does anyone have an idea why?

Related

Getting data from mysql in result array and batch updating

I need a quick solutions to this problem as I'm getting uninitialized offset 2 error codes
$this->db->select('bprice');
$this->db->from('items');
$this->db->limit(20);
$query = $this->db->get()->result_array();
$data = array();
foreach($query as $key => $value){
$data = array(
'branch_price' => (float)$value['bprice'][$key] + ((float)$value['bprice'][$key] * 0.30)
);
}
return $this->db->update_batch('items',$data);
$this->db->select('bprice');
$this->db->from('items');
$this->db->limit(20);
$query = $this->db->get()->result_array();
$data = array();
foreach($query as $query){
$data = array(
'branch_price' => (float)$query['bprice'] + ((float)$query['bprice'] * 0.30)
);
}
return $this->db->update_batch('items',$data);

Laravel - How to Update Dynamic Input Fields

In my Laravel-8, I have this code:
public function add(Request $request){
if( $request->ajax() ){
$rules = array(
'first_name.*' => 'required',
'country.*' => 'required'
);
$error = Validator::make($request->all(),$rules);
if($error->fails()){
return response()->json([
'error' => $error->errors()->all(),
]);
}
$first_name = $request->first_name;
$country = $request->country;
for( $count = 0; $count < count($first_name); $count++ ){
$data = array(
'first_name' => $first_name[$count],
'country' => $country[$count],
);
$insert_data[] = $data;
}
DynamicField::insert($insert_data);
return response()->json([
'success' => 'Data added Successfully',
]);
}
}
This successfully Inserts record.
How do I do the update to this same code?
I mean public function update ...

session userdata has null initials, is not inputted into the database

I have a code like this, the problem is when I input why the id_user value is "0".
even though the admin logged in is "1"
Is there anything missing in my script code?
Controller
public function tambah() {
// $this->session->set_userdata('upload_image_file_manager',true);
$kategori = $this->kategori_m->tampil();
$this->session->set_userdata('upload_image_file_manager',true);
// Validasi
$valid = $this->form_validation;
$valid->set_rules('judul_berita','Judul','required',
array( 'required' => 'Judul harus diisi'));
$valid->set_rules('isi_berita','Isi','required',
array( 'required' => 'Isi berita harus diisi'));
if($valid->run()) {
if(!empty($_FILES['gambar']['name'])) {
$config['upload_path'] = './resch/dev/admin/assets/media/';
$config['allowed_types'] = 'gif|jpg|png|svg|jpeg';
$config['max_size'] = '20480'; // 2 Mb
$this->load->library('upload', $config);
if(! $this->upload->do_upload('gambar')) {
// End validasi
$data = array( 'head_title' => 'Berita- Edutech Solution',
'title' => 'Tambah Berita',
'head_menu' => 'Berita',
'sub_title' => 'Total Berita',
'kategori' => $kategori,
'error' => $this->upload->display_errors(),
'isi' => 'superadmin/berita/tambah');
$this->load->view('superadmin/template/wrapper_admin', $data, FALSE);
// Masuk database
}else{
$upload_data = array('uploads' =>$this->upload->data());
// Image Editor
$config['image_library'] = 'gd2';
$config['source_image'] = './resch/dev/admin/assets/media/'.$upload_data['uploads']['file_name'];
$config['new_image'] = './resch/dev/admin/assets/media/thumbs';
$config['create_thumb'] = TRUE;
$config['quality'] = "100%";
$config['maintain_ratio'] = TRUE;
$config['width'] = 360; // Pixel
$config['height'] = 360; // Pixel
$config['x_axis'] = 0;
$config['y_axis'] = 0;
$config['thumb_marker'] = '';
$this->load->library('image_lib', $config);
$this->image_lib->resize();
$i = $this->input;
$slug = url_title($i->post('judul_berita'),'dash',TRUE);
$data = array( 'id_kategori' => $i->post('id_kategori'),
'id_user' => $this->session->userdata('user_name'),
'slug_berita' => $slug,
'judul_berita' => $i->post('judul_berita'),
'isi_berita' => $i->post('isi_berita'),
'jenis_berita' => $i->post('jenis_berita'),
'status_berita' => $i->post('status_berita'),
'gambar' => $upload_data['uploads']['file_name'],
// 'icon' => $i->post('icon'),
'keyword' => $i->post('keyword'),
'tanggal_publish'=> date('Y-m-d',strtotime($i->post('tanggal_publish'))).' '.$i->post('jam_publish'),
// 'tanggal_mulai' => $i->post('tanggal_mulai'),
// 'tanggal_selesai' => $i->post('tanggal_selesai'),
// 'urutan' => $i->post('urutan'),
'tanggal_post' => date('Y-m-d H:i:s'),
);
$this->berita_m->tambah($data);
$this->session->set_flashdata('sukses', 'Data telah ditambah');
redirect(base_url('superadmin/berita/jenis_berita/'.$i->post('jenis_berita')),'refresh');
}}else{
$i = $this->input;
$slug = url_title($i->post('judul_berita'),'dash',TRUE);
$data = array( 'id_kategori' => $i->post('id_kategori'),
'id_user' => $this->session->userdata('user_name'),
'slug_berita' => $slug,
'judul_berita' => $i->post('judul_berita'),
'isi_berita' => $i->post('isi_berita'),
'jenis_berita' => $i->post('jenis_berita'),
'status_berita' => $i->post('status_berita'),
'gambar' => $upload_data['uploads']['file_name'],
// 'icon' => $i->post('icon'),
'keyword' => $i->post('keyword'),
'tanggal_publish'=> date('Y-m-d',strtotime($i->post('tanggal_publish'))).' '.$i->post('jam_publish'),
// 'tanggal_mulai' => $i->post('tanggal_mulai'),
// 'tanggal_selesai' => $i->post('tanggal_selesai'),
// 'urutan' => $i->post('urutan'),
'tanggal_post' => date('Y-m-d H:i:s'),
);
$this->berita_m->tambah($data);
$this->session->set_flashdata('sukses', 'Data telah ditambah');
redirect(base_url('superadmin/berita/jenis_berita/'.$i->post('jenis_berita')),'refresh');
}}
// End masuk database
$data = array( 'head_title' => 'Berita- Edutech Solution',
'title' => 'Tambah Berita',
'head_menu' => 'Berita',
'sub_title' => 'Total Berita',
'kategori' => $kategori,
'isi' => 'superadmin/berita/tambah');
$this->load->view('superadmin/template/wrapper_admin', $data, FALSE);
}
in a model like this, I feel there is no problem
Model
public function tampil() {
$this->db->select('berita.*, user.nama, kategori.nama_kategori, kategori.slug_kategori');
$this->db->from('berita');
// Join dg 2 tabel
$this->db->join('kategori','kategori.id_kategori = berita.id_kategori','LEFT');
$this->db->join('user','user.id_user = berita.id_user','LEFT');
// End join
$this->db->order_by('id_berita','DESC');
$query = $this->db->get();
return $query->result();
}
// Tambah
public function tambah($data) {
$this->db->insert('berita',$data);
}
session userdata has null initials, not inputted to the database and
because I was confused, I skip. and create a function to update, but when the update function is executed it will give an error "too few arguments to functio"
I don't understand the problem.

Laravel Mqtt's subscription doesn't end

I receive an Mqtt message from Laravel and try to do some action, but if you subscribe, you only get one message and it takes about a minute to delay.
I referred to this at https://github.com/salmanzafar949/MQTT-Laravel.
Implementing Mqtttt motion was made by creating a separate controller.
My code is
<?php
namespace App\Http\Controllers;
use Salman\Mqtt\MqttClass\Mqtt;
use Illuminate\Http\Request;
class MqttController extends Controller{
public $token = "";
public function SendMsgViaMqtt(Request $request)
{
$mqtt = new Mqtt();
//$client_id = Auth::user()->id;/
$topic = $request->topic;
$token = $request->token;
$message = $request->message;
$output = $mqtt->ConnectAndPublish("test", $message, "");
if ($output === true)
{
if($token == "none" || !$token){
return "End";
}else{
$this->SubscribetoTopic($token);
}
}else{
return "Failed";
}
}
public function SubscribetoTopic($token)
{
$topic = 'test';
$this->token = $token;
$message = [];
$mqtt = new Mqtt();
$client_id = "";
$mqtt->ConnectAndSubscribe($topic, function($topic, $msg){
if($msg == "end"){
$message = [
'title' => '魚が釣れました',
'body' => '釣竿を確認してください',
'click_action' => 'Url'
];
}else if($msg == "no"){
$message = [
'title' => '測定できません',
'body' => '波が強すぎると測れません',
'click_action' => 'Url'
];
}else{
return "end";
}
return $this->sendCrul($this->token, $message);
}, "");
}
public function sendCrul($token, $message){
define('SERVER_API_KEY', 'APIKEY');
$tokens = $token;
$header = [
'Authorization: Key=' . SERVER_API_KEY,
'Content-Type: Application/json'
];
$payload = [
'to' => $tokens,
'notification' => $message
];
$curl = curl_init();
curl_setopt_array($curl, array(
CURLOPT_URL => "https://fcm.googleapis.com/fcm/send",
CURLOPT_RETURNTRANSFER => true,
CURLOPT_CUSTOMREQUEST => "POST",
CURLOPT_POSTFIELDS => json_encode( $payload ),
CURLOPT_HTTPHEADER => $header
));
$response = curl_exec($curl);
$err = curl_error($curl);
curl_close($curl);
if($err){
echo "cURL Error #:". $err;
}else{
return $response;
}
// return "ok";
}
}
If you're in trouble like me, let me know how.

CODEIGNITER - Parse error: syntax error, unexpected '=>' (T_DOUBLE_ARROW)

I know this has been frequently asked and has been answered a few times now but I can't fix my problem here using the ones that has already existed. I also just started to learn codeigniter. This is the code:
$draw = intval($this->input->get("draw"));
$start = intval($this->input->get("start"));
$length = intval($this->input->get("length"));
$movies = $this->movielist_model->get_movies();
$data = result();
foreach($movies->result() as $r) {
$data[] = result(
$r->title,
$r->price,
$r->rating
);
}
// IT SAYS THAT THE ERROR IS HERE:
$output = result(
"draw" => $draw,
"recordsTotal" => $movies->num_rows(),
"recordsFiltered" => $movies->num_rows(),
"data" => $data
);
echo json_encode($output);
exit();
}
Create a array $result and put that into output array, if you have more outputs you can still put a lots of things inside that array.
$result = [
"draw" => $draw,
"recordsTotal" => $movies->num_rows(),
"recordsFiltered" => $movies->num_rows(),
"data" => $data
];
$output [] = $result;
echo json_encode($output);
exit();
You should have array()
public function somefunction() {
$output = array();
$data = array();
$draw = intval($this->input->get("draw"));
$start = intval($this->input->get("start"));
$length = intval($this->input->get("length"));
$movies = $this->movielist_model->get_movies();
foreach($movies->result() as $r) {
$data[] = array(
'title' => $r->title,
'price' => $r->price,
'rating' => $r->rating
);
}
$output[] = array(
"draw" => $draw,
"recordsTotal" => $movies->num_rows(),
"recordsFiltered" => $movies->num_rows(),
"data" => $data
);
}
echo json_encode($output);
}

Resources