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);
}
Related
My requirement, I want to update the MYSQL table every 30 seconds. So I am using PHP sessions to store the visitor count . After 30 seconds , I will update session value to the table. It is working fine but while one time open and close the browser tab I can't get that session value.
For example if visitors open the page one time and close so session value is 1 , this value I can't able get and update in my table. So can you please help me.
Here is my code :
// add custom post content
function wp_post_view_blog_visit_count($content) {
$ip_addr = $_SERVER['REMOTE_ADDR'];
$post_id = get_the_ID();
if(isset($_SESSION['wp_blog_views_two'.$post_id.$ip_addr])) {
$_SESSION['wp_blog_views_two'.$post_id.$ip_addr] = ++$_SESSION['wp_blog_views_two'.$post_id.$ip_addr];
}else{
$_SESSION['wp_blog_views_two'.$post_id.$ip_addr] = 1;
}
$blog_view_count = $_SESSION['wp_blog_views_two'.$post_id.$ip_addr];
echo $blog_view_count.' SESSION VALUE'.'<br>';
$count_key = 'post_views_count_'.$post_id.$ip_addr;
//WordPress has a function to get custom field values, get_post_meta().It accepts three parameters
$count = (int) get_post_meta($post_id, $count_key, true);
echo $count.' FROM TABLE'.'<br>';
if($count == '' || $count == 0){
//the function to delete custom fields values is delete_post_meta()
delete_post_meta($post_id,$count_key); //delete the post meta table record
//Saving a custom field value in the database is as easy as getting it. The function to use is add_post_meta().
add_post_meta($post_id, $count_key, 1);//add the post meta table record
return $content .= $count.' Views'.'<br><br>';
}else{
/*
* Check the cookie is exist or not.
* If not the set cookie for some time interval and
* increase the count
*/
++$count;
if(isset($_SESSION["user".$post_id.$ip_addr])){
if(time()-$_SESSION["login_time_stamp".$post_id.$ip_addr] > 30){ //30 seconds
unset($_SESSION['user'.$post_id.$ip_addr]);
unset($_SESSION["login_time_stamp".$post_id.$ip_addr]);
unset($_SESSION['wp_blog_views_two'.$post_id.$ip_addr]);
//To update the value of an existing custom field use the function update_post_meta()
update_post_meta($post_id, $count_key, $count+$blog_view_count);//update the post meta mysql table
}
}else{
$_SESSION["user".$post_id.$ip_addr] = 'VIEWING'.$post_id.$ip_addr;
$_SESSION["login_time_stamp".$post_id.$ip_addr] = time();
}
}
return $content .= '<b style="color:red;">'.$count.'</b> Views'.'<br><br>';
}
add_filter('the_content', 'wp_post_view_blog_visit_count');
I have a form page in which many of the elements are saved to different tables and different rows in my db. In order to minimize db calls I would like to compare the data before and after form submission, then I can write a function which will only update data that has been changed. To accomplish this I am saving the array that I used to build the form in a session file:
$this->session->set_tempdata('form_values_'.$item['id'],json_encode($item), 86400);
On form submission I retrieve this data and compare it to the $_POST:
$pre_post = json_decode($_SESSION['form_values_'.$_POST['id']], true);
Everything works great except in a few textareas where there is a "." in my test data. For some reason these fields come back as not equal even though I'm not changing the data.
It is definitely the period that is causing the problem, when I remove it it works fine. On the other hand there are other textareas that have periods that are not causing problems.
I thought it might be codeigniter's XSS filtering, but I removed that and it made no difference.
Originally i was using serialize to encode the array for storage, but I switched to json_encode and again it made no difference.
Here is the code I am using to compare the values:
$pre_post = json_decode($_SESSION['form_values_'.$_POST['id']], true);
$post = $this->security->xss_clean($_POST);
foreach ($post as $key => $value) {
if( !isset($pre_post[$key]) || trim($value)!=trim($pre_post[$key]) ){
$post_post[$key] = $value;
}
}
Any ideas?
Try this code may be it help you
$select = "SELECT * FROM ".$table_name." WHERE ".$field_name ." = '".$value."'";
$result_latest = mysql_query($select) or trigger_error(mysql_error());
while($row = mysql_fetch_array($result_latest,MYSQL_ASSOC))
{
$data_new = array_intersect_key($row,$data);
foreach($data_new as $k=>$v)
{
if(strcmp($row[$k],$data[$k]) != 0)
{
$string .= '`'.$k.'` = "'.$data[$k].'" ,';
}
}
}
$string = rtrim($string, ",");
if($string != NULL){
$update_sql = "UPDATE ".$table_name." SET ".$string." WHERE ".$field_name." = "."'".$value."'";
$query = $CI->db->query($update_sql);
}
I'm new to Laravel and MySQL, i couldn't figure out how to use a single join query to get user, their posts, and post comments. I'm not sure if i'm doing it right, but there must be a better way to fetch posts and post comments in a structured way. This is what I've done so far. I'm using $username to lookout for every single post user has made in Posts table and then looping through each post to see if that specific post has any comments with post.id.
It's working perfectly, but i feel that it's a bit expensive way to loop through each single posts to find it's comments with an individual query. Is there a better way to do it in a single query and keep data structured so that i can easily populate my view?
public function user($username){
$user = User::where('username',$username);
if($user->count()){
$user = $user->first();
$posts = Posts::where('username', $username)->orderBy('created_at', 'DESC')->orderBy('at','DESC')->paginate(4);
if(count($posts)>0){
$i=0;
foreach($posts as $data){
$ago = date('Y-m-d', strtotime($data->created_at)).' '.$data->at;
$comments = Comments::where('post_id',$posts[$i]->id)->get();
$posts[$i]->at = ProfileController::getElapsedTime($ago);
$posts[$i]->comments = $comments;
$j=0;
foreach($posts[$i]->comments as $comments){
$c_time = date('Y-m-d', strtotime($comments->created_at)).' '.$comments->at;
$posts[$i]->comments[$j]->at = ProfileController::getElapsedTime($c_time);
$comment_user = User::where('username', $posts[$i]->comments[$j]->comment_user)->first();
$posts[$i]->comments[$j]->user_dp = $comment_user->dp_uri;
$posts[$i]->comments[$j]->name = $comment_user->name;
$j++;
}
//echo $posts[$i]->comments.'<br><br>';
$i++;
}
}
return View::make('profile.posts')
->with('user',$user)->with('posts', $posts);
}else{
return Response::view('errors.missing', array(), 404);
}
}
I am trying to get all the rows from a Google spreadsheet via a PHP/Zend script. This is the script I am using:
$service = Zend_Gdata_Spreadsheets::AUTH_SERVICE_NAME;
$client = Zend_Gdata_ClientLogin::getHttpClient('xxxxxxxxx', 'xxxxxxx', $service);
$spreadsheetService = new Zend_Gdata_Spreadsheets($client);
// Get spreadsheet key
$spreadsheetsKey = 'xxxxxxxxxxxxx';
$worksheetId = 'xxx';
// Get cell feed
$query = new Zend_Gdata_Spreadsheets_CellQuery();
$query->setSpreadsheetKey($spreadsheetsKey);
$query->setWorksheetId($worksheetId);
$cellFeed = $spreadsheetService->getCellFeed($query);
// Build an array of entries:
$ssRows = array();
$ssRow = array();
$titleRow = array();
$tableRow = 1;
foreach($cellFeed as $cellEntry) {
$row = $cellEntry->cell->getRow();
$col = $cellEntry->cell->getColumn();
$val = $cellEntry->cell->getText();
// Add each row as a new array:
if ($row != $tableRow) {
array_push($ssRows, $ssRow);
$ssRow = array();
// Move to the next row / new array
$tableRow = $row;
}
// Build the array of titles:
if ($row == 1) {
$titleRow[$col] = $val;
}
// Build the array of results with the title as the key:
else {
$key = $titleRow[$col];
$ssRow[$key] = $val;
}
}
// Pass the results array:
return array_reverse($ssRows);
This builds me an array with MOST of the details from the spreadsheet, however it always misses off the last entry - can anyone see what I am doing wrong, or is there a better way to get all the data from the spreadsheet?
The form is a 3 part form, based on different answers. On filling out one part, I want to display a URL back to the form, with some details from the first form pre-filled to make the second part of the form faster to fill out. This is all fine, it is simply the missing last entry that is the major problem!
Thanks!
Your code works like this:
if (next_row) {
data[] = current_row
current_row = array();
}
if (first_row) {
title_row logic
} else {
add cell to current_row
}
So you only add the rows to your collector once you go to the next row. This will miss the last row because you'll miss that last transition.
The easy fix is to add array_push($ssRows, $ssRow); right after the foreach loop. You will need to add a check for 0 rows, this should be skipped then.
Perhaps a more proper fix is to iterate by row, then by cell, rather than just by cell.
In my database I have a table of "weeks" and a table of "workouts". I would like to achieve something like the following:
Week 1
workout 1 title
workout 1 content
workout 2 title
workout 2 content
workout 3......
week 2
workout 1 title
workout 1 content
workout 2 title
workout 2 content
workout 3......
week 3.....
I've trying something like:
function get_weekly_content() {
$user_id = $this->session->userdata('id');
$weeks = $this->db->select('week_no')->where('user_id', $user_id)->get('weeks');
if($weeks->num_rows > 0) {
foreach($weeks->result() as $row) {
$week_no = $row->week_no;
$workouts = $this->db->where('user_id', $user_id)->where('week_no', $week_no)->get('workouts');
if($workouts->num_rows > 0) {
foreach($workouts as $workout) {
$workout_data[] = $workout;
}
}
$weekly_data[] = $workout_data;
}
return $weekly_data;
}
}
but maybe I have the wrong idea. I would then also need to display the data.
EDIT my question is, what would be the best way to achieve the above and get and array/object to loop through on a view page?
Thanks
Looping with in a loop is just fine, and your approach is appropirate. However!
Generally speaking you shouldn't run mysql queries inside of loops if there is any way to avoid it because queries are quite slow this will really degrade the performance of your script. Otherwise, the idea is correct. Try to write a query outside of the loops that puts all the relevant user data into a keyed array and then pull the information from the array while you're looping.
You're going to see problems with this line: $weekly_data[] = $workout_data; if $workouts->num_rows > 0... if it's the first loop, it will throw an error because $workout_data won't be set, and if it's subsequent loops then on any week that doesn't have results, it will display the previous week's data. You can fix this by setting/resetting $workout_data at the top of the inner loop:
$workout_data = array();
if($workouts->num_rows > 0) {
foreach($workouts as $workout) {
$workout_data[] = $workout;
}
}
function get_weekly_content() {
$user_id = $this->session->userdata('id');
$weeks = $this->db->select('week_no')->where('user_id', $user_id)->get('weeks');
$weekly_data = array();
if($weeks->num_rows > 0) {
foreach($weeks->result() as $row) {
$workout_data = array();
$week_no = $row->week_no;
$workouts = $this->db->where('user_id', $user_id)->where('week_no', $week_no)->get('workouts');
if($workouts->num_rows > 0) {
foreach($workouts as $workout) {
$workout_data[] = $workout;
}
}
$weekly_data[$week_no] = $workout_data;
}
}
return $weekly_data;
}
Then access the data:
$weekly_data = get_weekly_content();
foreach( $weekly_data as $week_no => $workout_data){
// do something with it.
}
That being said, I agree with #Ben D, you should think about your query and create one that can return all the results at once.