Magento, 1 db field not saved - magento

I have a problem with one field of the DB. With this code:
$expireMonth = Mage::getStoreConfig('points_options/config_points/expiration_period', Mage::app()->getStore()->getId());
if (!is_null($expireMonth) && ($expireMonth > 0)) {
$expireDate = date("Y-m-d H:i:s", strtotime("+" . $expireMonth . " month"));
} else {
$expireDate = NULL;
}
//die($expireDate);
//store in points history table
$this->_pointsModel->setCustomerId($this->_customer->getId())
->setOrdersId('welcome')
->setPointsPending($pointsForNewCustomer)
->setPointsComment(Mage::helper('points')->__('welcome points'))
->setDateAdded(date('Y-m-d H:i:s'))
->setPointsStatus(2)//confirmed
->setPointsType('WE')
->setStoreId(Mage::app()->getStore()->getId())
->setExpireDate($expireDate)
->save();
Every field is saved in the table, except for expire_date. If I uncomment the die($expireData), I see the correct value, something like 2012-01-13 13:21:12. The field is defined as:
`expire_date` datetime NULL
Any thoughts?
edit: The solution is:
$expireDate = date("Y-m-d H:i:s", strtotime("+" . $expireMonth . " months"));
Check out the "s" in my strtotime expression.

I know many attributes allow for some sort of formatting before writing and after reading. Have you tried setting the value as a unix timestamp instead?

Related

Lumen: Auto increment and Reset Transaction_ID Automatically every month

I trying to generate random transaction_id, with format "2000-yymmm-0000".
I already know how to set the transaction_id, but I have a problem with the auto-increment from "2000-yymm-0000" to "2000-yymm-0001", and reseting automatically to "2000-yymm-0000" at every new month.
I put this logic in different path of controller.
PS: I'm using Lumen 6.0 with Laravel 6.0.
I'm trying to create the increment with:
$number = sprintf('%04d', 0000);
$number++;
but it didn't work.
$year = 2000;
$time = date('ym');
$number = sprintf('%04d', 0000);
$transaction_id = $year . '-' . $time . '-' . $number;
$transaction_data = explode('-', $transaction_id);
$month = date("m", strtotime($transaction_data[0]));
I expect the result to automatically increment every time a new data is stored to the database. But the actual result is transaction_id being having always the same value 2000-yymm-0000.
What am I doing wrong?
I know it's weird to answer my own question, but i already find the solution.
in Models/Order.php
i create a function like this.
public function count()
{
$this->where(transaction_id)->count();
}
after that i call the function from Model/Order.php to OrdersController.php
public function create(Request $request)
{
$year = 2000;
$date = date('ym');
$total_data = $this->table->count();
$number = str_pad($total_data + 1, 4, 0, STR_PAD_LEFT);
$transaction_id = $year . '-' . $date . '-' . $number;
return $this->success('count all transaction id', $t_id);
}

Laravel chained jobs as array not working. Attempt to assign property of non-object

I'm trying to loop over multiple servers that need to run 1 at a time using Laravel's withChain. The first job completes just fine but the data I'm passing within the chained jobs gives me the
Attempt to assign property of non-object
When I log out the initial dispatched data it looks just like the constructed data in my array so I'm not sure what I'm doing wrong.
$new_jobs_array = [];
foreach ($this->wasRequest->nodes->sortByDesc('pivot.node_type') as $node) {
if ($node->pivot->node_type != 'WAS_DMGR')
{
$snode = strtolower($node->hostname);
$shortname = strtok($snode, '.');
$fileName = strtolower($mnemonic).'_'.$shortname.'_'.$reqId.'.json';
$sourceJsonPath = base_path() . "/json/was/" . $fileName;
$new_job = 'new BootStrapWasNode('. $node .', '. $this->wasRequest .', '.$sourceJsonPath.')';
array_push($new_jobs_array, $new_job);
} else {
$dmgr_node = $node;
}
}
//Log::info($new_jobs_array);
$dmgr_node_sname = strtok($this->wasRequest->nodes->where('pivot.node_type', 'WAS_DMGR')->pluck('hostname')[0], '.');
$fileName = strtolower($mnemonic).'_'.$dmgr_node_sname.'_'.$reqId.'.json';
$sourceJsonPath = base_path() . "/json/was/" . $fileName;
$this->wasRequest->status = 'Bootstrapping Nodes';
$this->wasRequest->save();
//Log::info("DMGR-------------------".$dmgr_node.", ".$this->wasRequest.", ".$sourceJsonPath);
BootStrapWasNode::withChain($new_jobs_array)->dispatch($dmgr_node, $this->wasRequest, $sourceJsonPath);
I can attach the log view if needed but there is a lot of data for each node. The issue is with the $new_nodes_array, the initial dispatch($dmgr_node,$this->wasRequest,$sourceJsonPath) completes without issue.
Was able to figure out the issue.
This line was incorrect
$new_job = 'new BootStrapWasNode('. $node .', '. $this->wasRequest .','.$sourceJsonPath.')';
It should be
$new_job = new BootStrapWasNode($node, $this->wasRequest, $sourceJsonPath);

How to use timezones in Laravel?

The user creates date in format like as: 12/23/2016 22:10
After this data should be sent convert to another timezone, for example GMT + 2:
12/23/2016 00:10
I can assume the date that I create should be saved in GTM 0, only after I can change timezone.
How can I use this mechanism in Laravel?
You can use Carbon to change the the timezone of a date as:
$date = Carbon\Carbon::parse('12/23/2016 22:10', 'GMT');
And to add +2 you can do as:
$date->addHours(2)
You can change the timezone for your application in: /config/app.php,
The default timezone is UTC. You can find all supported timezones here: http://php.net/manual/en/timezones.php
Mostly I'm agree with Amit Gupa answer, but the best way to manage timezone conversion isn't by adding hours, but by converting it on Carbon:
$yourdate->timezone('somecountrytimezone')
This way you won't have to worry about different time management between countries (Like daylight saving time) and just manage to get your works done.
Please refer do the documentation : http://carbon.nesbot.com/docs/#api-settersfluent
We can use parse and createFromFormat methods of Carbon to set our datetime as a certain timezone then use setTimezone to convert it to another timezone.
$date = "2022-08-05 12:00:00"; //set datetime for checking
$now = Carbon::now()->timezone('Europe/London')->format('Y-m-d H:i:s');
$createFrom = Carbon::createFromFormat('Y-m-d H:i:s', $date, 'Asia/Hong_Kong')->format('Y-m-d H:i:s');
$parse = Carbon::parse($date,'Asia/Hong_Kong')->setTimezone('Europe/London')->format('Y-m-d H:i:s');
$converted = Carbon::parse($date,'Asia/Hong_Kong')->timezone('Europe/London')->format('Y-m-d H:i:s');
outputs: when dd($now,$createFrom,$parse,$converted);
^ "2022-08-05 08:33:48"
^ "2022-08-05 12:00:00"
^ "2022-08-05 05:00:00"
^ "2022-08-05 05:00:00"
that's not related to laravel , it's just a php , so you can simply get the time-zone offset (exp GMT+3) then do like this :
$timeZoneOffset ---> for GMT+3 you put (3)
function getNewDateByTimeZone($date, $timeZoneOffset)
{
/* if the client Time zone is GMT */
if (!$timeZoneOffset || $timeZoneOffset == 0) {
$timeZoneOffset = "-0";
}
$op = $timeZoneOffset[0];
$timeZoneOffset = preg_replace('/[^0-9.]+/', '', $timeZoneOffset) * 60;
$userDate = date($date, time());
$timeStamp = strtotime($userDate);
$offsetTime = $op == '-' ? $timeStamp + $timeZoneOffset : $timeStamp - $timeZoneOffset;
return date("Y-m-d H:i", $offsetTime);
}
so like that you will save the date in GMT-0

Codeigniter CSV upload then explode

I have some code that uploads the CSV file to the specified folder, but it doesn't update the database.
public function do_upload()
{
$csv_path = realpath(APPPATH . '/../assets/uploads/CSV/');
$config['upload_path'] = $csv_path;
$config['allowed_types'] = '*'; // All types of files allowed
$config['overwrite'] = true; // Overwrites the existing file
$this->upload->initialize($config);
$this->load->library('upload', $config);
if ( ! $this->upload->do_upload('userfile'))
{
$error = array('error' => $this->upload->display_errors());
$this->layout->buffer('content', 'program/upload', $error);
$this->layout->render();
}
else
{
$image_data = $this->upload->data();
$fname = $image_data['file_name'];
$fpath = $image_data['file_path'].$fname;
$fh = fopen($fpath, "r");
$insert_str = 'INSERT INTO wc_program (JobRef, Area, Parish, AbbrWorkType, WorkType, Timing, TrafficManagement, Location, Duration, Start, Finish) VALUES '."\n";
if ($fh) {
// Create each set of values.
while (($csv_row = fgetcsv($fh, 2000, ',')) !== false) {
foreach ($csv_row as &$row) {
$row = strtr($row, array("'" => "\'", '"' => '\"'));
}
$insert_str .= '("'
// Implode the array and fix pesky apostrophes.
.implode('","', $csv_row)
.'"),'."\n";
}
// Remove the trailing comma.
$insert_str = rtrim($insert_str, ",\n");
// Insert all of the values at once.
$this->db->set($insert_str);
echo '<script type="text/javascript">
alert("Document successfully uploaded and saved to the database.");
location = "program/index";
</script>';
}
else {
echo '<script type="text/javascript">
alert("Sorry! Something went wrong please proceed to try again.");
location = "program/upload";
</script>';
}
}
}
When I run var_dump($fh); it shows: resource(89) of type (stream)
When I run var_dump($fpath) it shows: string(66) "/Applications/MAMP/htdocs/site/assets/uploads/CSV/wc_program.csv"
So it all uploads but what is wrong with it not updating the database?
I have tried all kinds of changing the fopen method but still no joy, I really need it to add to the database and the insert query and set query should do the trick but it doesn't.
Any help greatly appreciated!
You are not running any query on the database. You are mixing active record syntax with simple query syntax. The active record insert query will be executed by calling.
$this->db->insert('my_table');
db::set() does not actually query the database. It takes in a key/value pair that will be inserted or updated after db::insert() or db::update() is called. If you build the query yourself you need to use the db::query() function.
Review the active directory documentation.
You can use $this->db->query('put your query here'), but you lose the benefit of CodeIgniter's built in security. Review CodeIgniter's query functions.
I'll give you examples of just a few of the many ways you can insert into a database using CodeIgniter. The examples will generate the query from your comment. You will need to adjust your code accordingly.
EXAMPLE 1:
$result = $this->db
->set('JobRef', 911847)
->set('Area', 'Coastal')
->set('Parish', 'Yapton')
->set('AbbrWorkType', 'Micro')
->set('WorkType', 'Micro-Asphalt Surfacing')
->set('Timing', 'TBC')
->set('TrafficManagement', 'No Positive Traffic Management')
->set('Location', 'Canal Road (added PMI 16/07/12)')
->set('Duration', '2 days')
->set('Start', '0000-00-00')
->set('Finish', '0000-00-00')
->insert('wc_program');
echo $this->db->last_query() . "\n\n";
echo "RESULT: \n\n";
print_r($result);
EXAMPLE 2 (Using an associative array):
$row = array(
'JobRef' => 911847,
'Area' => 'Coastal',
'Parish' => 'Yapton',
'AbbrWorkType' => 'Micro',
'WorkType' => 'Micro-Asphalt Surfacing',
'Timing' => 'TBC',
'TrafficManagement' => 'No Positive Traffic Management',
'Location' => 'Canal Road (added PMI 16/07/12)',
'Duration' => '2 days',
'Start' => '0000-00-00',
'Finish' => '0000-00-00'
);
$this->db->insert('wc_program', $row);
// This will do the same thing
// $this->db->set($row);
// $this->db->insert('wc_program');
echo $this->db->last_query();
Example 1 and 2 are using the Active Record. The information is stored piece by piece and then the query is built when you make the final call. This has several advantages. It allows you to build queries dynamically without worrying about SQL syntax and order of the keywords. It also escapes your data.
EXAMPLE 3 (Simple Query):
$query = 'INSERT INTO
wc_program
(JobRef, Area, Parish, AbbrWorkType, WorkType, Timing, TrafficManagement, Location, Duration, Start, Finish)
VALUES
("911847","Coastal","Yapton","Micro","Micro-Asphalt Surfacing","TBC","No Positive Traffic Management","Canal Road (added PMI 16/07/12)","2 days","0000-00-00","0000-00-00")';
$result = $this->db->query($query);
echo $this->db->last_query() . "\n\n";
echo "RESULT: \n";
print_r($result);
This way leaves all the protection against injection up to you, can lead to more errors, and is harder to change/maintain.
If you are going to do it this way you should use the following syntax, which will protect against injection.
EXAMPLE 4:
$query = 'INSERT INTO
wc_program
(JobRef, Area, Parish, AbbrWorkType, WorkType, Timing, TrafficManagement, Location, Duration, Start, Finish)
VALUES
(?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?);';
$row = array(
911847,
'Coastal',
'Yapton',
'Micro',
'Micro-Asphalt Surfacing',
'TBC',
'No Positive Traffic Management',
'Canal Road (added PMI 16/07/12)',
'2 days',
'0000-00-00',
'0000-00-00'
);
$result = $this->db->query($query, $row);
echo $this->db->last_query() . "\n\n";
echo "RESULT: \n";
print_r($result);
CodeIgniter will replace each "?" in the query with the corresponding value from the array after it is escaped. You can use this to run many queries that are of the same form, but have different data just by updating the $row array and benefit from CI's built in security.

admin session user edit posts

In database I have a column acc_type as int, and I'm trying to code this if $_SESSION['accountTpye']==1 then allowed this user to edit the other users posts,
And should I use and instead of && ? " or , || ".
Example code:
if(isset($_SESSION['username']) && ($_SESSION['username']==$dnn2['author'] || $_SESSION['accc_type']==1['username'])) {
echo "<a href='edit.php'>Edit</a>";
}
i think this will resolve your problem :
if(isset($_SESSION['username']){
if( ($_SESSION['username']==$dnn2['author']) || ($_SESSION['acc_type']==1) ){
echo "<a href='edit.php'>Edit</a>";
}
}
if((isset($_SESSION['username']) && $_SESSION['username']==$dnn2['author']) || $_SESSION['acc_type']==1){
echo "<a href='edit.php'>Edit</a>";
}
This part doesn't make sense:
$_SESSION['acc_type']==1['username']
If you just remove that last ['username'] and then wrap the session username part to be the first part of the conditional so the acc_type one does not depend on it then things should be ok
UPDATE:
In your login.php file locate this part:
$req = mysql_query('select password,id from users where username="'.$username.'"');
$dn = mysql_fetch_array($req);
if($dn['password']==sha1($password) and mysql_num_rows($req)>0)
{
$form = false;
$_SESSION['username'] = $_POST['username'];
$_SESSION['userid'] = $dn['id'];
You need to also select the acc_type. ASSUMING it's a field in the users table, modify the query to read this:
'select password,id, acc_type from users where username="'.$username.'"'
Then make sure to set the session var:
$form = false;
$_SESSION['username'] = $_POST['username'];
$_SESSION['userid'] = $dn['id'];
$_SESSION['acc_type'] = $dn['acc_type'];
When you test this, make sure you log out then log bacak in again.

Resources