Convert MySQL to pdo statement with json - mysql

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);
/*******************************/
?>

Related

ErrorException Creating default object from empty value in Laravel 6

when I'm trying to update user I got this error
this error point out at $user->first_name = $request->input('first_name');
update method
public function update($id, Request $request){
$this->validate($request, array(
'first_name' => 'string|max:255',
'last_name' => 'string|max:255',
'email' => "string|email|max:255|unique:users,email,$id",
'password' => "sometimes|nullable |string|min:8,$id",
'avatar' => 'image|mimes:jpg,jpeg,gif,png,svg|max:2048',
));
$password = bcrypt(request('password'));
$user = User::where('email',$request['email'])->first();
$user->first_name = $request->input('first_name');
$user->last_name = $request->input('last_name');
if(!empty($request->password))
{
$user->password = $password;
}
if($request->hasFile('avatar')){
$avatar = $request->file('avatar');
$filename = time() . '.' . $avatar->getClientOriginalExtension();
Image::make($avatar)->resize(300, 300)->save( public_path('/images/avatars/' . $filename ) );
$user->avatar = $filename;
}
$user->roles()->detach();
if ($request['user']) {
$user->roles()->attach(Role::where('name','User')->first());
}
if ($request['editor']) {
$user->roles()->attach(Role::where('name','Editor')->first());
}
if ($request['admin']) {
$user->roles()->attach(Role::where('name','Admin')->first());
}
$user->save();
return redirect('admin/users')->with('success', 'user is successfully saved');
}
Your assignment $user is null because there is no record with the email you are providing.
Use findOrFail($request['email']) so that you throw a ModelNotFoundException in this scenario.
OR
$user = User::where('email',$request['email'])->first();
if(!is_null($user) { // check not null of $user here
$user->first_name = $request->input('first_name');
$user->last_name = $request->input('last_name');
}
References:
https://laravel.com/docs/5.7/eloquent#retrieving-single-models
https://laracasts.com/discuss/channels/laravel/errorexception-in-profilecontrollerphp-line-98-creating-default-object-from-empty-value
You should use FindOrFail method instead
so instead of using this line:
$user = User::where('email',$request['email'])->first();
use this:
$user = User::findOrFail($id);
so FindOrFail will get the user by id and if it does not exist it will fail and show 404 Not found.

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.'));
}
}
}

Yii2 display data from phpexcel in view before saving to database

I am still on the process of learning Yii 2 framework. I was able to create a form that uploads excel file then save to database using phpexcel. I want to enhance it in a way that the data from the uploaded excel will be displayed on a table in view so the user can check the data if they are the same with the excel file. After checking, the user will have two options whether CANCEL or CONTINUE.
Here is my controller method to read file and save:
public function importExcel($model, $readFile, $dir)
{
try {
$readFileType = \PHPExcel_IOFactory::identify($readFile);
$objReader = \PHPExcel_IOFactory::createReader($readFileType);
$objPHPExcel = $objReader->load($readFile);
}
catch(Exception $e) {
die('Error reading data from excel file.');
}
$sheet = $objPHPExcel->getSheet(0);
$highestRow = $sheet->getHighestRow();
$highestCol = $sheet->getHighestColumn();
for($row = 9; $row <= $highestRow; $row++) {
$rowData = $sheet->rangeToArray('A'. $row . ':' . $highestCol . $row, NULL, TRUE, FALSE);
$objPHPExcel->getActiveSheet()
->getStyle('A'. $row . ':' . $highestCol . $row)
->getNumberFormat()->setFormatCode('0000');
// ->setFormatCode( \PHPExcel_Style_NumberFormat::FORMAT_TEXT );
if($row == 9) {
continue;
}
$document = new Document();
$document->type_id = ($rowData[0][0] == 'Ordinance' ? 1 : 2);
$document->no = $rowData[0][1];
$document->series = $rowData[0][2];
$document->title = $rowData[0][3];
$document->author = $rowData[0][5];
$document->date_approved = date('Y-m-d', strtotime($rowData[0][8].' '.$rowData[0][9].' '.$rowData[0][10]));
$document->region_c = $model->region_c;
$document->province_c = $model->province_c;
$document->citymun_c = $model->citymun_c;
$document->catParent = 1;
$document->category_id = 1;
$document->file_url = $dir . '/unzip/' . $rowData[0][13];
$document->save();
}
}
I did this and it worked.
try {
$readFileType = \PHPExcel_IOFactory::identify($readFile);
$objReader = \PHPExcel_IOFactory::createReader($readFileType);
$objPHPExcel = $objReader->load($readFile);
}
catch(Exception $e) {
die('Error reading data from excel file.');
}
$sheet = $objPHPExcel->getSheet(0);
$highestRow = $sheet->getHighestRow();
$highestCol = $sheet->getHighestColumn();
for($row = 9; $row <= $highestRow; $row++) {
$rowData = $sheet->rangeToArray('A'. $row . ':' . $highestCol . $row, NULL, TRUE, FALSE);
$objPHPExcel->getActiveSheet()
->getStyle('A'. $row . ':' . $highestCol . $row)
->getNumberFormat()->setFormatCode('0000');
if($row == 9) {
continue;
}
$data[] = array(
'type' => $rowData[0][0],
'no' => $rowData[0][1],
'series' => $rowData[0][2],
'title' => $rowData[0][3],
'author' => $rowData[0][5],
'dateapproved' => date('Y-m-d', strtotime($rowData[0][8].' '.$rowData[0][9].' '.$rowData[0][10])),
'file' => $rowData[0][13]
);
}
$dataProvider = new ArrayDataProvider([
'allModels' => $data,
'pagination' => [
'pageSize' => 10,
],
]);
return $this->render('display', [
'dataProvider' => $dataProvider,
]);
}
If your rowData contain the data and is an array of the row read form excel you can do this
$provider = new ArrayDataProvider([
'allModels' => $rowData,
'pagination' => [
'pageSize' => 10,
],
]);
return $this->render('your:view', [
'provider' => $provider,
]);
and in your grdiView
<?= GridView::widget([
'dataProvider' => $provider,
......

mysql_num_rows() error

I am displaying an editable table in drupal with the following code
function _MYMODULE_sql_to_table($sql) {
$html = "";
// execute sql
$resource = db_query($sql);
// fetch database results in an array
$results = array();
while ($row = db_fetch_array($resource)) {
$results[] = $row;
$id = $row['id'];
$email = $row['email'];
$comment = $row['comment'];
// drupal_set_message('Email: '.$email. ' comment: '.$comment. ' id: '.$id);
}
// ensure results exist
if (!count($results)) {
$html .= "Sorry, no results could be found.";
return $html;
}
// create an array to contain all table rows
$rows = array();
// get a list of column headers
$columnNames = array_keys($results[0]);
// loop through results and create table rows
foreach ($results as $key => $data) {
// create row data
$row = array(
'edit' => l(t('Edit'),"admin/content/test/".$data['id']."/ContactUs", $options=array()),);
// loop through column names
foreach ($columnNames as $c) {
$row[] = array(
'data' => $data[$c],
'class' => strtolower(str_replace(' ', '-', $c)),
);
}
// add row to rows array
$rows[] = $row;
}
// loop through column names and create headers
$header = array();
foreach ($columnNames as $c) {
$header[] = array(
'data' => $c,
'class' => strtolower(str_replace(' ', '-', $c)),
);
}
// generate table html
$html .= theme('table', $header, $rows);
return $html;
}
// then you can call it in your code...
function _MYMODULE_some_page_callback() {
$html = "";
$sql = "select * from {contact3}";
$html .= _MYMODULE_sql_to_table($sql);
return $html;
}
However, I keep getting the mysql_num_rows() error as
Warning: mysql_num_rows(): supplied argument is not a valid MySQL result resource. What is causing it?
Which version of Drupal are you using?
try db_affected_rows()
or db_num_rows()