Site built on Code Igniter framework. I have two links (like and dislike). When you click the link, the correspond value increases or decreases. You can see the site: http://joke.guluzade.com/jokes/view/24
What I want: That user can change this value only once. I do it by cookies. For example, if user click to "like" link the value +5 became +6. Then if you click "dislike" the value must not change. User should have only one chance to like or dislike. Now it doesn't work correctly, if you click like you are able to click dislike too, but I want only change the lie or dislike value only one time.
How I do: I check if the cookie is set, function does nothing, if not it sets cookie and changes value. But if cookie set for like, when you click dislike it doesn't see that cookie.
Here is code:
function vote ($mm, $id){ //get the parameters (like or dislike and id)
$name = $mm;
$value = (int)$id;
$time = time()+3600;
if(isset($_COOKIE[$value])){
redirect($_SERVER['HTTP_REFERER']);
} else {
SetCookie($value, $name, $time);
if($name == "like"){
$this->db->select('like');
$this->db->where('id', $id);
$query = $this->db->get('jokes');
$data = $query->row_array();
$likes = $data['like'];
$likes++;
$dd = array();
$dd['like'] = $likes;
$this->db->where('id', $id);
$this->db->update('jokes', $dd);
redirect($_SERVER['HTTP_REFERER']);
} else {
$this->db->select('dislike');
$this->db->where('id', $id);
$query = $this->db->get('jokes');
$data = $query->row_array();
$likes = $data['dislike'];
$likes--;
$dd = array();
$dd['dislike'] = $likes;
$this->db->where('id', $id);
$this->db->update('jokes', $dd);
redirect($_SERVER['HTTP_REFERER']);
}
}
}
Can anybody say, what I do wrong?
use get_cookie('some_cookie') OR get_cookie('some_cookie',TRUE); instead of $cookie[$value].
moreover set cookie for full domain using
$cookie = array(
'name' => 'The Cookie Name',
'value' => 'The Value',
'expire' => '86500',
'domain' => '.some-domain.com',
'path' => '/',
);
set_cookie($cookie);
You can find the answer from following posts.
How can I set a cookie and then redirect in PHP?
http://www.tek-tips.com/viewthread.cfm?qid=1509045
Related
Can someone please guide me how I can fetch mysql row's value for "pk" to the $response variable to be able to allow the script to unfollow users automatically. I have already tried the script and it does unfollow when an pk id is provided but I want to automatically fetch it from mysql to be able to run it. Thank you for any help provided.
These are the methods I tried with no success:
$this->db->select('pk');
$this->model->from(INSTAGRAM_FOLLOW_TB);
$this->db->where("id = '11'");
$query1 = $this->db->get();
$result = $query1->result();
Main ID that only unfollow this ID- created by Mushfik Media,
$response = $i->unfollow($result);
I have also tried
$accounts = $this->model->fetch("*", INSTAGRAM_ACCOUNT_TB, "id = '11'");
$response = $i->unfollow($accounts->pk);
But didn't work. $NEED MYSQL DATA VALUE is where the value is supposed to be echoed but doesn't
case 'unfollow':
try {
$result = $i->getSelfUsersFollowing();
if(!empty($result) && $result->status == "ok" && !empty($result->users)){
$response = $i->unfollow($NEED MYSQL DATA VALUE);
$response = $response->status;
$CI =& get_instance();
$CI->load->model('Schedule_model', 'schedule_model');
$lang = $CI->db->insert(INSTAGRAM_FOLLOW_TB, array(
"pk" => $row->pk,
"name" => $row->username,
"type" => $data->schedule_type,
"uid" => $data->uid,
"account_id" => $data->account,
"account_name" => $data->name,
"created" => NOW
));
}
} catch (Exception $e){
$response = $e->getMessage();
}
break;
Maybe something like this to get your pk:
$query1 = $this->db->select('pk')
->from(INSTAGRAM_FOLLOW_TB)
->where('id', 11)
->get();
if( $query1->num_rows() == 1 ){
$row = $query1->row();
$response = $i->unfollow( $row->pk );
}
Regarding your information that you are trying to use $this when not in object context, because you are in a helper, you need to get the CI super object. So, if you were trying to use $this->db, you would do this:
$CI =& get_instance();
// Now you can use $CI->db
// and anything you would normally
// access via $this in a controller
// or model
OK, finally to show an example of how to order or limit a query:
$query1 = $this->db->select('pk')
->from(INSTAGRAM_FOLLOW_TB)
->where('id', 11)
->order_by('your_timestamp_field', 'ASC') // This would order by timestamp in ascending order
->limit(1) // This would limit to a single row
->get();
I use the default codeiginter pagination library. I tried implementing this in a previously created page which shows all vacancies, but since we are getting TOO many on the site, the performance is terrible. This is why I need pagination on this page. Note that this is not the cleanest solution, there is a new track going on which overhauls the entire page and starts from scratch. This is a quick & dirty solution because we need to keep it working on our live environment until the rework is done.
This is the controller code I have:
public function overviewVacancies($city = null)
{
$this->is_logged_in();
// Load Models
$this->load->model('vacancy/vacancies_model');
$this->load->model('perk/interests_model');
$this->load->model('perk/engagement_model');
$this->load->model('user/userSavedVacancies_model');
// Passing Variables
$data['title'] = lang("page_title_activities_overview");
$data['description'] = lang('meta_desc_activities');
$data['class'] = 'vacancy';
$data['engagements'] = $this->engagement_model->getAll();
$data['interests'] = $this->interests_model->getAllInterests();
$data['bread'] = $this->breadcrumbmanager->getDashboardBreadcrumb($this->namemanager->getDashboardBreadName("0"), $this->namemanager->getDashboardBreadName("1"));
$data['tasks'] = $this->interests_model->getAllTasks();
// Set session data
$this->session->set_userdata('previous',"http://$_SERVER[HTTP_HOST]$_SERVER[REQUEST_URI]");
$this->session->set_userdata('previous-title', "1");
$filterdata = array(
'interests' => $this->input->post('interests'),
'skills' => $this->input->post('skills'),
'fulldate' => $this->input->post('daterange'),
'location' => $this->input->post('location'),
'city' => $this->input->post('sublocality_level_1'),
'capital' => $this->input->post('locality')
);
if (!empty($filterdata['interests'])) {
$filterdata['interests'] = rtrim($filterdata['interests'], ";");
$filterdata['interests'] = str_replace(' ', '', $filterdata['interests']);
$filterdata['interests'] = str_replace(';', ',', $filterdata['interests']);
}
if (!empty($filterdata['skills'])) {
$filterdata['skills'] = str_replace(' ', '', $filterdata['skills']);
$filterdata['skills'] = explode(",", $filterdata['skills']);
}
//Manually clear the commune and city variables if the location was empty
if (empty($filterdata['location'])) {
$filterdata['city'] = '';
$filterdata['capital'] = '';
}
if($city == null){
$orgId = $this->organization_model->getOrgIdByName(LOCATION);
}
else{
$orgId = $this->organization_model->getOrgIdByName($city);
$data['bread'] = $this->breadcrumbmanager->getLocalBreadcrumb($this->namemanager->getDashboardBreadName("0"), $city, $data['title'], $data['vacancydetails']);
}
//Set the location to the subdomain automatically (e.g. when the link is clicked) so the activities of that subdomain only show up
if (!empty(LOCATION)) {
$data['title'] = sprintf(lang('page_title_local_activities'), ucwords(LOCATION));
$data['description'] = sprintf(lang('meta_desc_local_activities'), ucwords(LOCATION));
$filterdata['location'] = LOCATION;
$data['bgcolor'] = $this->localSettings_model->getBgColorHexValueForOrgId($orgId->org_id);
}
if (!empty($filterdata['fulldate'])) {
$splitfromandto = explode(" - ", $filterdata['fulldate']);
$filterdata['datefrom'] = $splitfromandto[0];
$filterdata['dateto'] = $splitfromandto[1];
} else {
$filterdata['datefrom'] = null;
$filterdata['dateto'] = null;
}
//Put these variables in the data variable so we can prefill our filters again with the previous values
//This is necessary because we don't use AJAX yet
$data['filterdata'] = $filterdata;
//Pagination : We do it here so we can re-use the filter query to count all our results
$this->load->library('pagination');
$data['all_vacancies'] = $this->vacancies_model->getFilteredVacancies($filterdata);
$pagconfig['base_url'] = base_url().VACANCY_OVERVIEW;
$pagconfig['total_rows'] = count($data['all_vacancies']);
$pagconfig['per_page'] = 1;
$pagconfig['uri_segment'] = 2;
$pagconfig['use_page_numbers'] = TRUE;
$this->pagination->initialize($pagconfig);
$data['links'] = $this->pagination->create_links();
$start = max(0, ( $this->uri->segment(2) -1 ) * $pagconfig['per_page']);
//This variable contains all the data necessary for a vacancy to be displayed on the vacancy overview page
$data['vacancies'] = $this->vacancies_model->getFilteredVacancies($filterdata, false, null, false, null, false, false, $pagconfig['per_page'], $start);
// Template declaration
$partials = array('head' => '_master/header/head', 'navigation' => '_master/header/navigation_dashboard', 'content' => 'dashboard/vacancy/overview', 'footer' => '_master/footer/footer');
$data['vacancygrid'] = $this->load->view('dashboard/vacancy/vacancygrid', $data, TRUE);
$this->template->load('_master/master', $partials, $data);
}
As you can see in the code i keep a variable called $filterdata, this contains all data which is used in our filters, since we don't use AJAX in this version, we need to pass it to the view every time to fill it up again and present it to the visitor.
However, using pagination this breaks because it just reloads my controller method and thus the values in $filterdata are lost.
How do I go about this?
Note: it does not have to be a clean solution, it just needs to work since this page is going offline in a couple of weeks anyway.
Thanks a lot in advance!
I have coded a internal messenger system for the company I work for and I am trying to make things easier for myself by making a admin panel for this so it can control the usernames, passwords and groups.
Basically I am trying to select a user from the array using a url ?user=username which will then return the user information and allow it to be changed. The problem I am having is to get the url to select the username in the array.
The array is basic:
$users = array(
'0' => array(
'username' => 'test',
'password' => 'test123',
'group' => 'office',
),
Like this?:
<?php
// get username from URL (GET METHOD)
$username=$_GET["username"];
// $users has all the info
foreach ($users as $u) {
// find the target user
if ($u["username"] == $username) {
// do something with $u
var_dump($u);
}
}
?>
Did you tried to do this:
$user_name = $users[0]["username"];
Try this (not tested)
$u = null;
foreach($user as $user) {
if(isset($_GET['user']) && $user['username'] == $_GET['user']) {
$u = $user;
}
}
$u variable should contains yours user record.
Since it's an array i assume you have multiple indexes. I guess a simple 'find' function might work.
function findUser($searchData, $users, $searchField) {
$retObj = array();
foreach ($users as $user) {
if (isset($user[$searchField]) && $user[$searchField] == $searchData) {
$retObj['username'] = $user['username'];
$retObj['password'] = $user['password'];
$retObj['group'] = $user['group'];
break;
}
}
return $retObj;
}
EDIT: Added searchField so u can do same for password and group. Searchdata is the value u are searching
I am new to yii. I've created a custom in button in CGridView that has a class of CButtonColumn. I'm just wondering how can I pass parameters that I can add to my php function in my model.
This is my custom button in the table
array(
'class'=>'CButtonColumn',
'template'=>'{approve}, {update},{delete}',
'buttons'=>array(
'approve' => array(
'label'=>'Approve',
'options'=>array(),
'click'=>$model->approveRegistrants("$user_id, $category", array("id"=>$data->user_id , "category"=>$data->category),
)
)
)
and this is my function is
public function approveRegistrants($user_id, $category){
$db = new PDO('mysql:host=localhost; dbname=secret; charset=utf8', 'Andy', '*****');
$getCounter = "SELECT registrants FROM counter order by registrants desc limit 1;";
$bool = false;
$show = '0';
do{
$result = $db->query($getCounter);
// $registrants = $db->query($getCounter);
// $result->setFetchMode(PDO::FETCH_ASSOC);
// $registrants = '1';
foreach ($result as $value){
$registrants = $value['registrants'];
echo 'hello'.$registrants.'</br>';
}
// $registrants = $result['registrants'];
// print_r($registrants);
$max_registrants = '3400';
if($max_registrants > $registrants){
// pdo that will use $updateCounterByOne
$updateCounterByOne = "UPDATE counter set registrants = registrants + 1 WHERE registrants = ". $registrants .";";
$updateCounter = $db->prepare($updateCounterByOne);
$updateCounter->execute();
// return affected rows
$returnAffectedRows = $updateCounter->rowCount();
$bool = true;
// break;
}
else{
echo "No more slot Available";
// break;
}
}while($returnAffectedRows == '0');
if($bool = true){
//sql syntax
$selectApprovedUser = "SELECT user_id FROM registrants WHERE user_id = '". $user_id ."';";
//pdo that will use $selectApprovedUser
$updateApprovedUser = "UPDATE registrants set approved = 'YES' where user_id = ". $selectApprovedUser .";";
$updateApproved = $db->prepare($updateApprovedUser);
$updateApproved->execute();
//pdo that will use $insertApprovedUser
$insertApprovedUser = "INSERT INTO approved_registrants (user_id, category, approved_date) VALUES ('".$user_id."', '".$category."', 'curdate()');";
$insertApproved = $db->prepare($insertApprovedUser);
$insertApproved->execute();
//execute trial
$selectSomething = "SELECT registrants from counter where tandem = '0'";
$doSelect = $db->prepare($selectSomething);
$doSelect->execute();
$hello = $doSelect->fetchAll();
echo $hello[0]['registrants'];
}
}
your issue is that you are bypassing the controller fully here.
buttons column is configured with the following parameters
'buttonID' => array(
'label'=>'...', // text label of the button
'url'=>'...', // a PHP expression for generating the URL of the button
'imageUrl'=>'...', // image URL of the button. If not set or false, a text link is used
'options'=>array(...), // HTML options for the button tag
'click'=>'...', // a JS function to be invoked when the button is clicked
'visible'=>'...', // a PHP expression for determining whether the button is visible
)
See CButtonColumn for details.
As you can see click has to be a js function that will be called on clicking the button. You can rewrite your button like this
array(
'class'=>'CButtonColumn',
'template'=>'{approve}, {update},{delete}',
'buttons'=>array(
'approve' => array(
'label'=>'Approve',
'options'=>array(),
// Alternative -1 Url Method -> will cause page to change to approve/id
'url'=>'array("approve","id"=>$data->id)',
// Alternative -2 Js method -> use 1,2 not both
'click'=>'js:approve()',
)
)
)
in your CGridView configuration you add
array(
....
'id'=>'gridViewID', //Unique ID for grid view
'rowHtmlOptionsExpression'=> 'array("id"=>$data->id)',
)
so that each row has the unique ID, ( you can do the same to a button, but it slightly more difficult as $data is not available there)
in your js function you can do this.
<script type="text/javascript">
function approve(){
id = $(this).parent().parent().attr("id");
<?php echo CHtml::ajax(array( // You also can directly write your ajax
'url'=>array('approve'),
'type'=>'GET',
'dataType'=>'json',
'data'=>array('id'=>'js:id'),
'success'=>'js:function(json){
$.fn.yiiGridView.update("gridViewID",{});
// this will refresh the view, you do some other logic here like a confirmation box etc
}'
));?>
}
</script>
Finally your approve action
class YourController extend CController {
......
public function actionApprove(){
id = Yii::app()->request->getQuery('id');
$dataModel = MyModel::model()->findByPk($id); // This is the model has the $user_id, and $category
....
$OtherModel->approve($dataModel->user_id,$dataModel->category) // if approve is in the same model you can self reference the values of category and user_id directly no need to pass as parameters.
// Do some logic based on returned value of $otherModel->approve()
// return the values from the approve() function and echo from here if required back to the view, directly echoing output makes it difficult to debug which function and where values are coming from .
Yii::app()->end();
}
I'm building an android app that uses Phil Sturgeon's RESTful Server for CodeIgniter as a RESTful API.
When the android app makes a POST request to register a user with facebook oauth data the method below is called when it reaches server side. It works, but if one or more of the optional params is empty it will insert a 0 into my database.
How do I prevent this? I'd much prefer it enters nothing at all or null.
function fb_register_post(){
if($this->get_request_method() != "POST"){
$this->response('',406);
}
$oauth_email = $this->input->post('OAUTH_EMAIL');
$oauth_uid = $this->input->post('OAUTH_UID');
$oauth_provider = $this->input->post('OAUTH_PROVIDER');
$first_name = $this->input->post('FIRST_NAME');
$last_name = $this->input->post('LAST_NAME');
if(!empty($oauth_provider) and !empty($oauth_uid) and !empty($oauth_email) and !empty($first_name) and !empty($last_name)){
if(filter_var($oauth_email, FILTER_VALIDATE_EMAIL)){
$new_member_insert_data = array(
'first_name' => $first_name,
'last_name' => $last_name,
'email' => $oauth_email,
'OAUTH_EMAIL' => $oauth_email,
'OAUTH_PROVIDER' => $oauth_provider,
'OAUTH_UID' => $oauth_uid,
//OPTIONAL DATA
'gender' => $this->post('GENDER'),
'hometown' => $this->post('HOMETOWN'),
'bio' => $this->post('BIO'),
'birthday' => $this->post('BIRTHDAY')
);
$this->load->model('membership_model');
$data['user'] = $register = $this->membership_model->oauth_register($new_member_insert_data);
$this->response($data, 200);
}
}else{
$message = array('message' => 'FAIL');
$this->response($message, 201);
}
$message = array('message' => 'FAIL!');
$this->response($message, 200); // 200 being the HTTP response code
}
The model function being called is :
function oauth_register($new_member_insert_data)
{
$insert = $this->db->insert('users', $new_member_insert_data);
if($insert){
$UID = $new_member_insert_data['OAUTH_UID'];
$q = $this->db->query("SELECT * FROM users WHERE OAUTH_UID = $UID LIMIT 1 ") or die(mysql_error());
if($q->num_rows() > 0)
{
foreach($q->result() as $row)
{
$data[] = $row;
}
return $data;
}
}
else
{
return false;
}
}
The issue is your post parameters is passing an empty string '' for the value (at least that's what the $_POST array will see it as). Then you try to insert this into an numeric column and Mysql magically is casting it to 0 -- even if you've got another default value set.
The best thing you can do is check the parameters for being empty before adding them to the $new_member_insert_data array any values that are numeric (assuming this array is used to construct the insert statement). Below is an explicit example of not setting array members that have empty values:
//assuming all non-optional details have values
$new_member_insert_data = array(
'first_name' => $first_name,
'last_name' => $last_name,
'email' => $oauth_email,
'OAUTH_EMAIL' => $oauth_email,
'OAUTH_PROVIDER' => $oauth_provider,
'OAUTH_UID' => $oauth_uid
) ;
//OPTIONAL DATA
$gender = $this->post('GENDER')? $this->post('GENDER'):null;
if(!empty($gender)){
$new_member_insert_data['gender'] = $gender;
}
$hometown = $this->post('HOMETOWN')? $this->post('HOMETOWN'):null;
if(!empty($hometown)){
$new_member_insert_data['hometown'] = $hometown;
}
...etc...
You can also prevent this on the client request side by not putting any thing without an value into your post parameters, but I always protect against this on the webservice side, not just the client POST request side.
You'll also see this happen with dates and timestamps... when you try to set them to '' tehy end up like 0000-00-00 00:00:00.
You can turn on a strict mode in Mysql that will cause inserts fail when you try to stuff an empty string into a numeric field or other non-character field (I highly recommend against this though).