Update sales_flat_order_item table in Magento - mysql

I've a scenario in which I need to update sales_flat_order_item table after creation of order. I am using following code:
$combine_array = Array
(
[22500] => 257
[4500] => 258
)
foreach ($combine_array as $item=>$key)
{
$data = array('discount_amount'=> $item);
$orderModel = Mage::getModel('sales/order_item')->load($key)->addData($data);
try{
$orderModel->setItemId($key)->save();
}catch(Exception $e)
{
echo $e->getMessage();
}
}
But this code is not working. Kindly suggest how to update.

I tried the same code and it is updating the data perfectly. Below is my code:-
$combine_array = array(225010 => 108, 45010 => 109);
foreach ($combine_array as $item => $key) {
$data = array('discount_amount' => $item);
$orderModel = Mage::getModel('sales/order_item')->load($key)->addData($data);
try {
$orderModel->setItemId($key)->save();
} catch (Exception $e) {
echo $e->getMessage();
}
}

Related

Laravel: DB::transaction() in try catch not working

I am using manual DB transactions in my controller.
public function exportUsers(){
DB::beginTransaction();
try{
$data = new \App\Models\User();
$excelData = $data->getMemberData();
$reportGeneratedOn = date('dMY');
$report_file_name = 'All_Members_'.$reportGeneratedOn.'.xls';
DB::table('settings')->where('id',1)->update(['user_export_status_id'=>2]);
$excelHTML = view('administrator.member.excel',compact('excelData'))->render();
$reader = new \PhpOffice\PhpSpreadsheet\Reader\Html();
$spreadsheet = $reader->loadFromString($excelHTML);
$writer = \PhpOffice\PhpSpreadsheet\IOFactory::createWriter($spreadsheet, 'Xls');
$fileName = md5('allmembers_'. microtime()).".xls";
$path = storage_path('app/temp/');
$writer->save( $path . $fileName );
$excel_file_content = file_get_contents( $path . $fileName );
$data = $this->S3Upload($fileName , env('S3_MEMBERS_EXPORT_PATH'), env('S3_MEMBERS_EXPORT_URL'), $excel_file_content,$report_file_name );
if ( $data['status'] ){
DB::table('settings')->where('id',1)->update(['user_export_status_id'=>3]);
DB::table('settings')->where('id',1)->update(['user_export_path'=>$data['preSignedUrl']]);
if( is_file($path . $fileName) ) {
#unlink( $path . $fileName );
}
}
DB::commit();
return response()->json(['error' => 0, 'code' => 200, 'message' => 'Please download the generated excel.','status'=>3, 'report_url' => $data['preSignedUrl']], 200);
}
catch(\Exception $e){
DB::rollBack();
return response()->json(['error' => 1, 'code' => 200, 'message' => 'An error occured while generating the report.'.$e->getMessage().' : '.$e->getFile().'-'.$e->getLine()], 200);
}
}
But using this I got an error like below
Error : An error occured while generating the report.DOMDocument::loadHTML(): htmlParseEntityRef: no name in Entity, line: 2855 :
C:\wamp64\www\O2X\Trunk\Web\vendor\phpoffice\phpspreadsheet\src\PhpSpreadsheet\Reader\Html.php-619
My database has a user_export_status_id field which at first has value 1..When an export starts it get updated as 2. But after I got error, it is not roll backed to 1. Dataabse still has value 2.

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

Cannot pass whitespace separated value to Query

My project with PHP and MySql stuck here ,
$searchfriend = "Jason";
$status = query("SELECT status FROM users.profile WHERE name = ?" , $searchfriend );
The above statement works quite well.
When I replace,
$searchfriend = "Jason R"
It's not working. What is the solution ?
I have created my own query function with PDO.
function query()
{
$sql = func_get_arg(0);
$parameters = array_slice(func_get_args(), 1);
static $handle;
if (!isset($handle))
{
try
{
$handle = new PDO("mysql:dbname=" . DATABASE . ";host=" . SERVER, USERNAME, PASSWORD);
$handle->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);
}
catch (Exception $e)
{
trigger_error($e->getMessage(), E_USER_ERROR);
exit;
}
}
$statement = $handle->prepare($sql);
if ($statement === false)
{
trigger_error($handle->errorInfo()[2], E_USER_ERROR);
exit;
}
$results = $statement->execute($parameters);
if ($results !== false)
{
return $statement->fetchAll(PDO::FETCH_ASSOC);
}
else
{
return false;
}
}

PDO Mutiple Query execute and catch error

i need to execute three queries and find out which query is failed in PDO.
My config php
$dbh = new PDO("mysql:host=$hostname;dbname=$dbname", $username, $password,array( PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,PDO::ATTR_AUTOCOMMIT, FALSE));
My class file
class myClass
{
function lastbench()
{
try {
$q1 = "select * from user";
$code_pre = $dbh->prepare($q1);
$code_pre->execute();
if(!$code_pre)
{
throw new Exception("no table called user");
}
$q2 = "select * from userprofile";
$code_pre2 = $dbh->prepare($q2);
$code_pre2->execute();
if(!$code_pre2)
{
throw new Exception("no Profile table");
}
}
catch ( Exception $e)
{
$e->getMessage();
}
}
}
Any idea how to get the specific block is not executing..

Kohana 3.2 select issue

I have table with 'servers' name in my db. So when I want to add there some data with that code it's just ok:
public function action_add()
{
$serverGameId = (int)Arr::get($_POST, 'serverGameId', '');
$newServerName = Arr::get($_POST, 'newServerName', '');
try
{
$server = new Model_Server();
$server->Name = $newServerName;
$server->GameId = $serverGameId;
$server->save();
}
catch(ORM_Validation_Exception $e)
{
echo json_encode(array("success" => false, "errors" => $e->errors('validation')));
return false;
}
$this->request->headers['Content-Type'] = 'application/json';
echo json_encode(array("success" => true, "serverId" => $server->Id));
return true;
}
Here is a model:
class Model_Server extends ORM {
protected $_table_name = 'servers';
public function rules()
{
return array(
'Name' => array(
array('not_empty'),
)
);
}
}
But I have problem when I try to select it from the table:
public function action_servers()
{
$gameId = (int)Arr::get($_POST, 'gameId', '');
if($gameId == -1) return false;
try
{
$servers = ORM::factory('server')
->where('GameId', '=', $gameId)
->find_all();
}
catch(ORM_Validation_Exception $e)
{
echo json_encode(array("success" => false, "errors" => $e->errors('validation')));
return false;
}
$this->request->headers['Content-Type'] = 'application/json';
echo json_encode(array("success" => true, "servers" => $servers, "gameId" => $gameId));
return true;
}
I already try to solve problem with change code inside of try block on:
$servers = DB::select('servers')->where('GameId', '=', $gameId);
Even when I try just get all my servers from db without '->where' it's doesn't work.
Any ideas?
Try print_r($servers); inside try block to see what you get from model.
And $servers is some class with results - use foreach to get result (one by one)
$results = array();
foreach($servers as $row) {
//echo $row->Name;
$results[] = $row->Name;
}
Or
$results = array();
foreach($servers as $row) {
//echo $row->as_array();
$results[] = $row->as_array();
}