cakePHP: saving data in one column - php

i'm trying to count the views of a post using cakephp but the saving is not happinging using this code
$this->autoRender=false;
$unformattedData = $this->GeneralNews->findById($id);
$data = $unformattedData['GeneralNews'];
$total = $data['views'];
$total = $total+1;
$this->GeneralNews->views =$total;
print_r($this->GeneralNews->views);
$this->GeneralNews->save($this->request->data);
the print_r show me the views that's already on the table adding to them +1 .. but it's never saved in the DB .. what is the problem ?

Try this code :
$unformattedData = $this->GeneralNews->findById($id);
$unformattedData['GeneralNews']['views'] = $unformattedData['GeneralNews']['views'] + 1;
$this->GeneralNews->save($unformattedData);

Perhaps even easier:
$this->GeneralNews->id = $id;
$views = $this->GeneralNews->field('views');
$this->GeneralNews->saveField('views', $views + 1);
Hope this helps.

Related

Update One JSON Field in Database - CodeIgniter

I have a JSON field called 'spec' and there are about 10 other items in this in JSON format. I need to only update the quantity.
Although when I try this method, it deletes everything else in it and just sets spec = quantity.
Heres what I have so far.
$pass_coupon_id = $this->pass_coupon_id();
$coupon_array = $this->db->query("SELECT * FROM coupon WHERE coupon_id='$pass_coupon_id'")->result_array();
foreach ($coupon_array as $row) {
$spec = json_decode($row['spec'], true);
}
$quantity_new = $spec['quantity'] - 1;
$data2 = array(
'spec' => json_encode(array(
'quantity'=> $quantity_new
)));
$this->db->where('coupon_id', $pass_coupon_id);
$this->db->update('coupon', $data2);
You need to overrite only this one field and update whole field in query.
<?php
$pass_coupon_id = $this->pass_coupon_id();
$coupon_array = $this->db->query("SELECT * FROM coupon WHERE coupon_id='$pass_coupon_id'")->result_array();
// i don't know what you're using, but using foreach to extract single row isn't good solution. Look for sth like result_row() maybe.
$coupon = $coupon_array[0];
$spec = json_decode($coupon, true);
$new_quantity = $spec['quantity'] - 1;
$spec['quantity'] = $new_quantity;
$new_spec = json_encode($spec);
$this->db->where('coupon_id', $pass_coupon_id);
$this->db->update('coupon', $new_spec);
Depending on the database, the best solution would be using specific function to ommit updating whole structure - https://stackoverflow.com/a/34987329/2926214

transform sql query to Fluentpdo query

i have this sql query written in php:
$query = sprintf("UPDATE bank_info SET
amount_dollar = amount_dollar +'$amount_dollar' ,
amount_euro = amount_euro + '$amount_euro' ,
amount_local = amount_local + '$amount_local'
WHERE bank_id = '$bank_id' ");
this query works fine, but i want to transform this query using FluentPDO.
i want to use arrays to SET the values .
for example:
$table='bank_info'; //table name
$arrVal=array(); //values needs to be SET
$arrVal['amount_dollar = amount_dollar+?']=$amount_dollar;
$arrVal['amount_euro = amount_euro+?']=$amount_euro;
$arrVal['amount_local = amount_local+?']=$amount_local;
$arrWhere=array(); //where condition
$arrWhere['bank_id']=$bank_id;
this is the query:
$query = $this->pdo->update($table)->set($arrVal)->where($arrWhere);
$query->execute();
I think the problem is in the $arrVal, cant find the proper way to SET and add value to the current value for a column in the table.
I used array to select and get values from the DB/tables for many times so i think the $arrWhere is not the problem.
well, found the answer,
for ex.:
This is working for me:
$id = 5;
$field = 'stock';
$amount = 1;
$increment = array($field => new FluentLiteral($field.' + '.$amount));
$fpdo->update('products')->set($increment)->where('id', $id)->execute();

extracting values from Mysql query

i am confused about how to extract values from a query, and place them into specific variable, when i don't know before hand what the name of the value will be.
it might be easier to show you what i mean.
the images below are the returned values, grouped by heading i.e Total_responded, Percent_responded etc.
so the first row will have under the column Responce the value Poached with a Percent_responded of 16.66667.
however the next row will have under column Responce $scrambled with a Percent_responded of 83.333333
i now want to place each of these values into individual variables like:
$poached , $poachedPercentage, $scrambled, $scrambledPercentage etc
i attempted to do it below, but produced the wrong figures. this is also not a cost effective way to do it. so, i would really appricaite some advice on how to extract the values
$getPollResult = results();
while ($row = mysqli_fetch_array ($getResult , MYSQLI_ASSOC))
{
$responce = safe_output(round($row['RESPONCE']));
$percentage = safe_output(round($row['Percent_responded']));
if($responce = 'Poached')
{
$percentageOne = $percentage;
$poached = $responce;
}
if ($responce = 'Scrambled')
{
$percentageTwo = $percentage;
$scrambled = $responce;
}
// echo " $percentagePoached $percentageScrambled ";die();
}
Use
$responce = trim($row['RESPONCE']);
Instead Of
$responce = safe_output(round($row['RESPONCE']));
Also, Change in if condition = to ==.
you can use "variable variables" (PHP Docs) to achieve that:
while ($row = mysqli_fetch_array ($getResult , MYSQLI_ASSOC))
{
$responce_name = trim($row['RESPONCE']);
$percentage_name = $responce_name . "Percentage";
$percentage = safe_output(round($row['Percent_responded'])); //don't know what safe_output() does
$$percentage_name = $percentage; //notice the double "$" here
}
your PHP variables will then look like this:
$PoachedPercentage = 17;
$ScrambledPercentage = 83;
// and so on....

Codeigniter post view count function -

Hello i'm trying to make a post count function based on the codeigniter framework and what i done so far works great looking by my side. The function is complete and everything works fine.
But i have a question here from some experts to tell me that this is the correct ussage of the function and non of the above will harm my page loading. The function is accesed by jQuery get function on every click on the post.
First i'm checking if there is an ip address and if the ip address date inserted is more then 24 hours if its more i'm deleting the current row and then checking again becuase of the previous select its still remembering the last ip address and inserting again with new datime.
And other question should i make cleanjob every week or similar for all ip addreses ?
Here is my code:
function show_count($post_id){
$ip = $this->input->ip_address();
$this->db->select('ip_address,data');
$this->db->from('post_views');
$this->db->where('ip_address',$ip);
$query = $this->db->get();
foreach ($query->result() as $row){
$ip_address = $row->ip_address;
$data = $row->data;
}
if(isset($ip_address) && time() >= strtotime($data) + 8640){
$this->db->where('ip_address',$ip);
$this->db->delete('post_views');
}
$this->db->select('ip_address');
$this->db->from('post_views');
$this->db->where('ip_address',$ip);
$query = $this->db->get();
foreach ($query->result() as $row){
$ip_address_new = $row->ip_address;
}
if(!isset($ip_address_new) && $ip_address_new == false){
$date = new DateTime('now', new DateTimeZone('Europe/Skopje'));
$this->db->set('views', 'views+ 1', false);
$this->db->where('post_id',$post_id);
$this->db->update('posts');
$data = array(
'ip_address'=>$ip,
'data'=>$date->format("Y-m-d H:i:s")
);
$this->db->insert('post_views',$data);
}
}
Thanks, any suggestions will be appreciate.
Instead of doing lots of queries to increment unique views on your posts, you should use and set cookies and have a fallback method if cookies are not enabled.
$post_id = "???"
if(isset($_COOKIE['read_articles'])) {
//grab the JSON encoded data from the cookie and decode into PHP Array
$read_articles = json_decode($_COOKIE['read_articles'], true);
if(isset($read_articles[$post_id]) AND $read_articles[$post_id] == 1) {
//this post has already been read
} else {
//increment the post view count by 1 using update queries
$read_articles[$post_id] = 1;
//set the cookie again with the new article ID set to 1
setcookie("read_articles",json_encode($read_articles),time()+60*60*24);
}
} else {
//hasn't read an article in 24 hours?
//increment the post view count
$read_articles = Array();
$read_articles[$post_id] = 1;
setcookie("read_articles",json_encode($read_articles),time()+60*60*24);
}

Zend Date giving me zeroes, why?

More problems with dates.
Basically I'm trying to populate a table with some datetime values from Zend. The datatype of the column that I'm trying to populate is 'datetime'. However, no matter which constant I try the column is always populated with zeroes. I've tried Zend_Date::ISO_8601, Zend_Date::DATETIME, Zend_Date::now() to no avail. Pleas help.
Here's the code:
if(!$exists){
$date_time = Zend_Date::DATETIME;
/*
* Create the new site record
*/
$site_row = $site_table->createRow();
//if(isset($n_r['id'])) $row->id = $n_r['id'];
$site_row->name = $n_r['name'];
$site_row->active = 1;
$site_id = $site_table->total() + 1;
$address_id = $address_table->total() + 1;
$site_row->id = $site_id;
$site_row->address_id = $address_id;
/*
* Create the address record to go with it
*/
$address_row = $address_table->createRow();
$address_row->postcode = $n_r['postcode'];
$address_row->address_line1 = $n_r['name'];
$address_row->start_date = $date_time;
$address_row->id = $address_id;
$address_row->save();
$array[] = $site_row->toArray();
$site_row->save();
/*
* Create the new site2address record to go with it
*/
$site2address_row = $site2address_table->createRow();
$site2address_row->site_id = $site_id;
$site2address_row->address_id = $address_id;
$site2address_row->start_date = $date_time;
}else{
$array[] = $exists;
}
mySQL expects input for DATETIME columns to be
YYYY-MM-DD HH:MM:SS
independent from the locale you are using. I can't see a Zend constant for that, you may need to format it yourself.
you can use mysql function like NOW() for more convenience way. if you are at mysql code bellow may work for you.
$address_row->start_date = new Zend_Db_Expr('NOW()');

Categories