"message": "Creating default object from empty value", in postman - json

public function addcart($request)
{
$patient_id = config('api.current_user.patient_id') ? config('api.current_user.patient_id') : 0;
$patient = Patient::find($patient_id);
$patient_diagnostic_cart = #unserialize($patient->diagnostic_cart);
$response = [];
if (!empty($patient_diagnostic_cart)) {
if (in_array((int)$request->test_id, $patient_diagnostic_cart)) {
// abort(400, "Test allready added");
$message = "Test allready added";
} else {
array_push($patient_diagnostic_cart, (int)$request->test_id);
$patient->diagnostic_cart = serialize($patient_diagnostic_cart);
$patient->save();
$message = "Test added";
}
} else {
$patient_diagnostic_cart = (array)(int)$request->test_id;
$patient->diagnostic_cart = serialize($patient_diagnostic_cart);
$message = "Test added";
$patient->save();
}
$response = [
'message' => $message,
'test_id' => array_values(unserialize($patient->diagnostic_cart)),
];
$data = json_decode(json_encode($response, true));
return $data;
}

Related

Connecting Application to Mysql Database CPanel, utf8_general_ci

I have software or an application on a MacBook called Nano Hotel Booking, I am trying to connect it to my CPanel server but I get the error Unknown collation: 'utf8_general_ci'. Everything else works besides the error for UTF8 I have checked the setting on the Data
`
<?php
$database_host = "localhost";
$database_user = "12345";
$database_password = "12345";
$database_name = "12345";
$db_access_token = "";
$return_format = (isset($_REQUEST['return_format'])) ? $_REQUEST['return_format'] : 'json';
$res = array('success' => true, 'errormsg' => '', 'data' => '');
try
{
$filename = (isset($_FILES['uploadedfile']['name'])) ? $_FILES['uploadedfile']['name'] : '';
if(trim($filename))
{
$upload_dir = 'data';
$ar = explode('___', basename($_FILES['uploadedfile']['name']));
if(sizeof($ar) != 3) throw new Exception('Bad file name '.basename($_FILES['uploadedfile']['name']));
if(!trim($ar[0]) || !trim($ar[1])) throw new Exception('Bad folder name');
if(!trim($ar[2])) throw new Exception('Bad file name '.$ar[2]);
if(!file_exists($upload_dir))
{
if(!#mkdir($upload_dir, 0777)) throw new Exception('Can not create folder '.$upload_dir);
}
$upload_dir .= '/'.trim($ar[0]);
if(!file_exists($upload_dir))
{
if(!#mkdir($upload_dir, 0777)) throw new Exception('Can not create folder '.$upload_dir);
}
$upload_dir .= '/'.trim($ar[1]);
if(!file_exists($upload_dir))
{
if(!#mkdir($upload_dir, 0777)) throw new Exception('Can not create folder '.$upload_dir);
}
$upload_dir .= '/'.trim($ar[2]);
if(file_exists($upload_dir)) #unlink($upload_dir);
if(!move_uploaded_file($_FILES['uploadedfile']['tmp_name'], $upload_dir))
throw new Exception('Can not upload file '.$upload_dir);
} else
{
$params = $_REQUEST;
$action = (isset($_REQUEST['action'])) ? $_REQUEST['action'] : '';
if(!$action) throw new Exception('Action not found.');
$enc_request = (isset($_REQUEST['enc_request'])) ? $_REQUEST['enc_request'] : '';
$params = #json_decode(trim(base64_decode($enc_request)));
if($params == false) throw new Exception('Request is not valid');
$params = (array)$params;
// Connect user
$s_key = '';
if(isset($params['db_access_token']))
{
$s_key = $params['db_access_token'];
}
if($s_key !== $db_access_token) throw new Exception('Bad user.');
$controller = new apiController($database_host, $database_user, $database_password, $database_name);
if($action === 'checkconnection') throw new Exception('ok');
if(method_exists($controller, $action) === false ) throw new Exception('Action is invalid.');
$controller->request = $params;
$res['data'] = $controller->$action();
}
} catch(Exception $e)
{
$res['success'] = 0;
$res['errormsg'] = $e->getMessage();
}
switch($return_format)
{
case 'json': print(json_encode($res)); exit; break;
case 'xml': print(arrayToXml($res)); exit; break;
}
class apiController
{
public $request = array();
protected $conn;
public function __construct($host = '', $user = '', $psw = '', $dbname = '')
{
#$this->conn = mysqli_connect($host, $user, $psw, $dbname);
if(!$this->conn) throw new Exception(mysqli_connect_errno().' '.mysqli_connect_error());
#mysqli_query($this->conn, "SET CHARACTER SET utf8_general_ci");
#mysqli_query($this->conn, "set names utf8");
#mysqli_query($this->conn, "SET collation_connection = utf8_general_ci");
}
public function select()
{
$sql = (isset($this->request['sql'])) ? $this->request['sql'] : '';
$array = array();
if(is_array($sql))
{
foreach($sql as $value)
{
$arr = $this->selectOne($value);
$array[] = (sizeof($arr) > 0) ? $arr[0] : array();
}
} else
{
$array = $this->selectOne($sql);
}
if($this->conn) #mysqli_close($this->conn);
return $array;
}
public function selectOne($sql = '')
{
if(!trim($sql)) throw new Exception('Empty sql.');
$offset = (isset($this->request['offset'])) ? (int)$this->request['offset'] : 0;
$limit = (isset($this->request['limit'])) ? (int)$this->request['limit'] : 20;
if($limit) $sql .= ' LIMIT '.$offset.', '.$limit;
$result = mysqli_query($this->conn, $sql);
if(!$result) throw new Exception(mysqli_error($this->conn));
$rows = mysqli_num_rows($result);
if($rows <= 0)
{
mysqli_free_result($result);
mysqli_close($this->conn);
return array();
}
$array = array();
$fields = mysqli_num_fields($result);
while ($row = mysqli_fetch_row($result))
{
$onerow = array();
for ($i=0; $i < $fields; $i++) $onerow[] = $row[$i];
$array[] = $onerow;
}
mysqli_free_result($result);
return $array;
}
public function execute()
{
$sql = (isset($this->request['sql'])) ? $this->request['sql'] : '';
$array = array();
if(is_array($sql))
{
foreach($sql as $value)
{
$array = $this->executeOne($value);
}
} else
{
$array = $this->executeOne($sql);
}
if($this->conn) #mysqli_close($this->conn);
return $array;
}
public function executeOne($sql = '')
{
$lastid = '';
$result = null;
if(!trim($sql)) throw new Exception('Empty sql.');
$str = strtoupper($sql);
if((strpos($str, 'CREATE') !== false)
&& (strpos($str, 'TABLE') !== false)
)
{
$sql = str_ireplace ('AUTOINCREMENT' , 'AUTO_INCREMENT', $sql);
$sql = str_ireplace ('COLLATE NOCASE' , '', $sql);
}
if((strpos($str, 'INSERT') !== false)
&& (strpos($str, 'INTO') !== false)
&& (strpos($str, 'VALUES') !== false)
&& (strpos($str, '(0,') !== false)
)
{
$result = mysqli_query($this->conn, 'SET SQL_MODE="NO_AUTO_VALUE_ON_ZERO"');
if(!$result) throw new Exception(mysqli_error($this->conn));
}
$result = mysqli_query($this->conn, $sql);
if(!$result) throw new Exception(mysqli_error($this->conn));
if((strpos($str, 'INSERT') !== false)
&& (strpos($str, 'INTO') !== false)
&& (strpos($str, 'VALUES') !== false)
)
{
$result = mysqli_query($this->conn, 'SELECT LAST_INSERT_ID()');
if (mysqli_num_rows($result) > 0)
{
while ($row = mysqli_fetch_row($result))
{
$lastid = $row[0];
break;
}
}
}
$array = array();
$array[] = array($lastid);
if($result !== true) mysqli_free_result($result);
return $array;
}
public function getFieldFromSql($sql = '', $def = '')
{
if(!$sql) return $def;
$this->request['offset'] = 0;
$this->request['limit'] = 1;
$arr = $this->selectOne($sql);
if(sizeof($arr) == 0) return $def;
if(sizeof($arr[0]) == 0) return $def;
return $arr[0][0];
}
public function getFieldsFromSql($sql = '', $def = '')
{
if(!$sql) return $def;
$this->request['offset'] = 0;
$this->request['limit'] = 1;
$arr = $this->selectOne($sql);
if(sizeof($arr) == 0) return $def;
return $arr[0];
}
public function getArrayFromSql($sql = '')
{
if(!$sql) return array();
$this->request['offset'] = 0;
$this->request['limit'] = 100000;
return $this->selectOne($sql);
}
public function runScript()
{
$php = (isset($this->request['sql'])) ? trim($this->request['sql']) : '';
$nano = $this;
$php_res = #eval($php);
if($this->conn) #mysqli_close($this->conn);
if(is_array($php_res))
{
if(sizeof($php_res) > 0)
{
if(is_array($php_res[0])) return $php_res;
}
return array($php_res);
}
$array = array();
$array[] = array($php_res);
return $array;
}
}
?>
`
I have tried changing the UTF8 to almost everything else.

Can't Import Excel data to Mysql

I've following the step from this website [https://www.webslesson.info/2018/04/how-to-import-excel-data-into-mysql-database-using-codeigniter.html#comment-form][1]
but when I trying to import the data, my database data still empty
My Import Function in Controller :
public function import()
{
if(isset($_FILES["file"]["name"]))
{
$path = $_FILES["file"]["tmp_name"];
$object = PHPExcel_IOFactory::load($path);
foreach($object->getWorksheetIterator() as $worksheet)
{
$highestRow = $worksheet->getHighestRow();
$highestColumn = $worksheet->getHighestColumn();
for($row=2; $row<=$highestRow; $row++)
{
$customer_name = $worksheet->getCellByColumnAndRow(0, $row)->getValue();
$address = $worksheet->getCellByColumnAndRow(1, $row)->getValue();
$city = $worksheet->getCellByColumnAndRow(2, $row)->getValue();
$postal_code = $worksheet->getCellByColumnAndRow(3, $row)->getValue();
$country = $worksheet->getCellByColumnAndRow(4, $row)->getValue();
$data[] = array(
'CustomerName' => $customer_name,
'Address' => $address,
'City' => $city,
'PostalCode' => $postal_code,
'Country' => $country
);
}
}
$this->pppmodel->insert($data);
echo 'Data Imported successfully';
}
}
My model :
public function insert($data)
{
$this->db->insert('tbl_customer', $data);
}
}
Please help me

array saving cakephp 3 savemany

Hi can someone know this i am beginner in Cakephp i tried to upload multiple images but it wont save.
Controller:
public function add() {
if ($this->request->is('post')) {
//$data = $this->request->getData();
if(!empty($_FILES['photo']['name'])){
$count = count($_FILES['photo']['name']);
for ($i=0; $i < $count; $i++) {
$filename = $_FILES['photo']['name'][$i];
$type = $_FILES['photo']['type'][$i];
$tmp = $_FILES['photo']['tmp_name'][$i];
$error = $_FILES['photo']['error'][$i];
$size = $_FILES['photo']['size'][$i];
$uploadPath = '../uploads/files/';
$file[$i]['user_id'] = $this->Auth->user('id');
$file[$i]['filename'] = $filename;
$file[$i]['file_location'] = $uploadPath;
$file[$i]['file_type'] = $type;
$file[$i]['file_size'] = $size;
$file[$i]['file_status'] = 'Active';
$file[$i]['created'] = date("Y-m-d H:i:s");
$file[$i]['modified'] = date("Y-m-d H:i:s");
}
$table = TableRegistry::get('files');
$entities = $table->newEntities($file);
if($table->saveMany($entities)) {
$this->Flash->success(__('File has been uploaded and inserted successfully.'));
return $this->redirect(['action' => 'index']);
} else {
$this->Flash->error(__('Unable to upload file, please try again.'));
}
} else {
$this->Flash->error(__('Please choose a file to upload.'));
}
}
}
but when i tried to debug all good but in saving it wont work! does my code has problem, can someone help me how to fix my add function
View:
echo $this->Form->input('photo[]', ['type' => 'file','multiple' => 'true','label' => 'Upload Multiple Photos']);
You are trying to save one record once using saveMany().
public function add()
{
if ($this->request->is('post')) {
$table = TableRegistry::get('files');
$uploadPath = '../uploads/files/';
if(!empty($_FILES['photo'])){
foreach ($_FILES['photo'] as $EachPhoto) {
$data[] = [
'user_id' => $this->Auth->user('id'),
'filename' => $EachPhoto['name'],
'file_location' => $uploadPath,
'file_type' => $EachPhoto['type'],
'file_size' => $EachPhoto['size'],
'file_status' => 'Active',
'created' => date("Y-m-d H:i:s")
];
}
$entities = $table->newEntities($data);
if($this->Files->saveMany($entitie)) {
$this->Flash->success(__('File has been uploaded and inserted successfully.'));
return $this->redirect(['action' => 'index']);
} else {
$this->Flash->error(__('Unable to upload file, please try again.'));
}
} else {
$this->Flash->error(__('Please choose a file to upload.'));
}
}
}

Send mail on actionCreate

I have a system that works by the intranet and I would like to know how best to send an alert email in actionCreate?
I did as below, the email is sent correctly, but if the internet is offline an unfriendly error message appears.
public function actionCreate()
{
$model = new Todolist();
if ($model->load(Yii::$app->request->post())) {
$file = $model->uploadImage();
if ($model->save()) {
if ($file !== false) {
$idfolder = Yii::$app->user->identity->id;
if(!is_dir(\Yii::$app->getModule('task')->params['taskAttachment'])){
mkdir(\Yii::$app->getModule('task')->params['taskAttachment'], 0777, true);
}
$path = $model->getImageFile();
$file->saveAs($path);
}
Yii::$app->session->setFlash("task-success", "Atividade incluída com sucesso!");
\Yii::$app->mailer->compose('#app/mail/task')
->setFrom('intranet#sicoobcrediriodoce.com.br')
->setTo($model->responsible->email)
->setSubject(Yii::$app->params['appname'].' - '.\Yii::$app->getModule('task')->params['taskModuleName']. ' - Nova Tarefa : #'. $model->id)
->send();
return $this->redirect(['index']);
} else {
// error in saving model
}
}
return $this->render('create', [
'model' => $model,
]);
}
Try this (don't save model if email not sended)
public function actionCreate()
{
$model = new Todolist();
if ($model->load(Yii::$app->request->post())) {
$file = $model->uploadImage();
$transaction = $model->getDb()->beginTransaction();
try{
if ($model->save()) {
if ($file !== false) {
$idfolder = Yii::$app->user->identity->id;
if(!is_dir(\Yii::$app->getModule('task')->params['taskAttachment'])){
mkdir(\Yii::$app->getModule('task')->params['taskAttachment'], 0777, true);
}
$path = $model->getImageFile();
$file->saveAs($path);
}
Yii::$app->session->setFlash("task-success", "Atividade incluída com sucesso!");
\Yii::$app->mailer->compose('#app/mail/task')
->setFrom('intranet#sicoobcrediriodoce.com.br')
->setTo($model->responsible->email)
->setSubject(Yii::$app->params['appname'].' - '.\Yii::$app->getModule('task')->params['taskModuleName']. ' - Nova Tarefa : #'. $model->id)
->send();
return $this->redirect(['index']);
}
}
catch(Exception $e)
{
$transaction->rollBack();
throwe $e;
//unlik savedFile if exist
}
}
return $this->render('create', [
'model' => $model,
]);
}
or use mail queue to save mail in databases and send via cron

Convert MySQL to pdo statement with json

I am having an issue with getting this working with PDO not sure how to do it. I tried but kept getting an error. I will keep trying to figure it out. If anyone can point me in the write direction would be a big help
/** Function to Add Product **/
function add_product() {
$data = json_decode(file_get_contents("php://input"));
$prod_name = $data->prod_name;
$prod_desc = $data->prod_desc;
$prod_price = $data->prod_price;
$prod_quantity = $data->prod_quantity;
print_r($data);
$qry = 'INSERT INTO product (prod_name,prod_desc,prod_price,prod_quantity) values ("' . $prod_name . '","' . $prod_desc . '",' .$prod_price . ','.$prod_quantity.')';
$qry_res = mysql_query($qry);
if ($qry_res) {
$arr = array('msg' => "Product Added Successfully!!!", 'error' => '');
$jsn = json_encode($arr);
// print_r($jsn);
}
else {
$arr = array('msg' => "", 'error' => 'Error In inserting record');
$jsn = json_encode($arr);
// print_r($jsn);
}
}
/** Function to Get Product **/
function get_product() {
$qry = mysql_query('SELECT * from product');
$data = array();
while($rows = mysql_fetch_array($qry))
{
$data[] = array(
"id" => $rows['id'],
"prod_name" => $rows['prod_name'],
"prod_desc" => $rows['prod_desc'],
"prod_price" => $rows['prod_price'],
"prod_quantity" => $rows['prod_quantity']
);
}
print_r(json_encode($data));
return json_encode($data);
}
what I tried and I get no data inserting
/** Function to Add Product **/
function add_product() {
$data = json_decode(file_get_contents("php://input"));
$prod_name = $data->prod_name;
$prod_desc = $data->prod_desc;
$prod_price = $data->prod_price;
$prod_quantity = $data->prod_quantity;
print_r($data);
$qry = "INSERT INTO product (prod_name,prod_desc,prod_price,prod_quantity) VALUES (:prod_name,:prod_desc,:prod_price,:prod_quantity)";
$q = $conn->prepare($qry);
$q->execute(array(':prod_name'=>$prod_name,
':prod_desc'=>$prod_desc,
':prod_price'=>$prod_price,
':prod_quantity'=>$prod_quantity,
));
$qry_res = mssql_query($qry);
if ($qry_res) {
$arr = array('msg' => "Product Added Successfully!!!", 'error' => '');
$jsn = json_encode($arr);
// print_r($jsn);
}
else {
$arr = array('msg' => "", 'error' => 'Error In inserting record');
$jsn = json_encode($arr);
// print_r($jsn);
}
}
db setup
<?php
/****** Database Details *********/
$host = "localhost";
$user = "root";
$pass = "";
$database = "shopping";
$con = mysql_connect($host,$user,$pass);
if (!$con) {
die('Could not connect: ' . mysql_error());
}
//echo 'Connected successfully';
mysql_select_db($database,$con);
/*******************************/
?>