I am trying to determine if the database Update performed in my model was successful, pass the status of it (successful or not successful) ultimately to my view so that I can display a div appropriately. So far, it's worked as long as the model update worked, but it is not working when it's not. I'm using flashdata to pass the data through the controller.
My model:
public function editTicket($ticket)
{
$q = $this->db->where('ticketId', $ticket['ticketId']);
$q = $this->db->update('tickets', $ticket);
$results = $this->db->affected_rows();
return $results;
}
My Controller:
public function editExistingTicket()
{
$this->load->model('tickets');
$date = date("Y-m-d H:i:s");
$ticket = array(
'ticketId' => $this->input->post('ticketId'),
'category' => $this->input->post('category'),
'headline' => $this->input->post('headline'),
'description' => $this->input->post('description'),
'assigned' => $this->input->post('assigned'),
'status' => $this->input->post('status'),
'priority' => $this->input->post('priority'),
'lastUpdated' => $date
);
if ($this->tickets->editTicket($ticket)){
$this->session->set_flashdata('edit', '1');
} else {
$this->session->set_flashdata('edit', '0');
}
}
My View (the relevant parts):
var edited = '<?php echo $this->session->flashdata('edit'); ?>';
if (edited == '1') {
$('#editMessage').slideDown('slow');
setTimeout(function(){$('#editMessage').slideUp('slow')}, 3000);
//sessionStorage.setItem('edit', '0');
} else if (edited == '2') {
$('#editFailMessage').slideDown('slow');
setTimeout(function(){$('#editFailMessage').slideUp('slow')}, 3000);
//sessionStorage.setItem('edit', '0');
}
Any ideas on what I did wrong?
Thanks for the help!
Well, in the controller you are setting the flashdata to 0 if the ticket is updated unsuccessfully:
$this->session->set_flashdata('edit', '0');
But as you can see in the view you are expecting the variable visited to be 2:
} else if (edited == '2') {
and then the error box will appear.
You should fix your values and i think everything will be fine.
Related
I'm stuck at updating table row using api in codeigniter,
i already have read tutorial from code tutsplus
but there's no spesific to do it,
so i tried by myself and got stuck :-(
url request:
http://localhost/work/bnilife/v1/signup/user/post?nopol=a1b2c3d4e5&username=agus&password=kucingtikus&captcha=c12ds
Here's the json respon:
{
"error": "error :-( "
}
My Controller look like this below:
public function user_post()
{
date_default_timezone_set('Asia/Jakarta');
$datestring ="%Y-%m-%d %H:%i:%s";
$time =time();
$datetime =mdate($datestring, $time);
$data = array (
'nopol' => $this->input->get_post('nopol'),
'username' => $this->input->get_post('username'),
'password' => sha1($this->input->get_post('password')),
'created_at' => $datetime,
'updated_at' => $datetime
);
$result = $this->signup_m->signup_insert($data);
if($result) {
$this->response($data, 200);
} else {
$this->response(array('error' => 'error :-( '),400);
}
}
My model:
public function signup_insert($data) {
// Query to check whether username already exist or not
$condition = "nopol=" . "'" . $data['nopol'] . "'" ;
$this->db->where($condition);
$this->db->update('user', $data); }
Is there any something wrong or misstype,
thank you guys
i'm new at this stuff.
You can check codeigniter documentation how are working Database methods http://www.codeigniter.com/userguide3/database
public function signup_insert($data) {
$this->db->where('nopol',$data['nopol']);
return $this->db->update('user', $data);
}
In your case you need and return else you can't use the method as $result as it will be equal to NULL..
Check and CI Form Validation library as you don't validate your input data (even escaped) it may generate problems.
And importantly, you should write proper method names: signup_insert should INSERT not UPDATE.
'nopol' => $this->input->get_post('nopol') in this change to 'nopol' => $this->input->get_post('no_polis'),
also $this->db->where($condition) $condition is not defined.
Like #svetlio said,
i add some solution if nopol is typo(misstype) or null.
it will return false,
so i add some code to do it.
like this below:
if ($this->db->affected_rows() === 1) {
return true;
} else {
return false;
}
}
so it wont be like:
return $this->db->update('user', $data);
The model:
function validate()
{
$this->db->where('username',$this->input->post('username'));
$this->db->where('password',md5($this->input->post('password')));
$query = $this->db->get('memberships');
if($query->num_rows() == 1)
{
return TRUE;
}
}
function validate_admin()
{
$this->db->where('adminname',$this->input->post('username'));
$this->db->where('password',md5($this->input->post('password')));
$query = $this->db->get('admin');
if($query->num_rows() == 1)
{
return TRUE;
}
}
The controller
function validate_credentials()
{
$this->load->model('membership_model');
if($this->membership_model->validate())
{
$this->db->where('username',$this->input->post('username'));
$get_profile_info = $this->db->get('memberships');
if($get_profile_info->num_rows() > 0){
foreach ($get_profile_info->result() as $row)
{
$info = array('firstname' => $row->firstname,
'lastname' => $row->lastname,
'email_address' => $row->email_address
);
}
$data = array(
'username' => $this->input->post('username'),
'password' => $this->input->post('password'),
'firstname' => $info['firstname'],
'lastname' => $info['lastname'],
'email_address' => $info['email_address'],
'is_logged_in' => true
);
$this->session->set_userdata($data);
redirect('/site/main_menu');
}}
else if($this->membership_model->validate_admin())
{
echo "admin";
}
else
{
redirect('login');
}
}
The if else if statement is not working correctly. The program test the first condition and if it returns false skips the second condition even if that is TRUE and execute the else statement. I'm not sure what is going worng here.
Refactor your one controller method into different methods - one for Members and one for Admin to start. And because you are calling separate database tables would suggest having a separate model for each.
Because you are interacting with a database table getting the profile information should happen in a model (not the controller).
This is a personal preference but i would set the session data in a model as well. Also there might be issues with your foreach and then getting the value $info['first name'].
Validate the form data first before sending to your database. Its safer and its better for your users - if they forget to put in the password you want to show them the form again with a helpful message. http://ellislab.com/codeigniter/user-guide/libraries/form_validation.html
and remember when in doubt -- echo it out.
I want to add form validation if the ip_address duplicated just
stay on current page or show me any kind of message.
this is the model code
public function add_vote($option_id)
{
$this->db->insert($this->votes_table, array(
'option_id' => $option_id,
'ip_address' => $this->input->ip_address(),
'timestamp' => time()
));
return ($this->db->affected_rows() == 1) ? TRUE : FALSE;
}
this is the controler
public function vote($poll_id, $option_id)
{
if ( ! $this->poll_lib->vote($poll_id, $option_id))
{
$data['base_styles'] = 'public_html/res/css/base.css';
$data['title'] = 'Sorry an error occured';
$data['error_message'] = $this->poll_lib->get_errors();
$this->load->view('header');
$this->load->view('www/posts/postclose', $data);
}
else
{
redirect('posts', 'refresh');
}
}
hear if i add new vote it's shows me database error as the column is duplicate so i don't want to show that, if it redirect me to any other page will be great if stay on current page still ok or any pop up message.
Do a check before inserting into database.
public function add_vote($option_id)
{
$query = $this->db->get_where($this->votes_table, array('ip_address' => $this->input->ip_address()));
if($query->num_rows() < 1)
{ $this->db->insert($this->votes_table, array(
'option_id' => $option_id,
'ip_address' => $this->input->ip_address(),
'timestamp' => time()
));
return "Successfully Inserted";
}else{
return "Duplicate";
}
}
In your controller handle the response and display accordingly
I'm wondering what is the best message to pass back the success or failure message from the model to the controller? The success message is easy because we can pass the data back. However, for failures, we can only pass FALSE and not the callback result of the failure.
What is the best method?
Here is method one:
Here is the model:
function get_pkg_length_by_id($data) {
$this->db->where('id', $data['pkg_length_id']);
$result = $this->db->get('pkg_lengths');
if($result->num_rows() > 0 ) {
return $result->row();
}
else {
return false;
}
}
In the controller, I will do
function show() {
if(get_pkg_length_by_id($data) {
//pass success message to view
}
else {
//Pass failure message to view
}
Here is version 2:
In Model
function get_pkg_length_by_id($data) {
$this->db->where('id', $data['pkg_length_id']);
$result = $this->db->get('pkg_lengths');
if($result->num_rows() > 0 ) {
$result['status'] = array(
'status' => '1',
'status_msg' => 'Record found'
);
return $result->row();
}
else {
$result['status'] = array(
'status' => '0',
'status_msg' => 'cannot find any record.'
);
return $result->row();
}
}
In Controller
function show() {
$result = get_pkg_length_by_id($data);
if($result['status['status']] == 1) {
//pass $result['status'['status_msg']] to view
}
else {
//pass $result['status'['status_msg']] to view
}
I can't say for certain which is best. I can say that I often use choice # 2, where I pass errors from the server, often doing so in a specific form that any subclass of my controller can parse and send to the view.
Also, in your show() function, the else is extraneous, once you return, you will break out of the function , so you can just do :
if($result->num_rows() > 0 ) {
$result['status'] = array(
'status' => '1',
'status_msg' => 'Record found'
);
//the condition is met, this will break out of the function
return $result->row();
}
$result['status'] = array(
'status' => '0',
'status_msg' => 'cannot find any record.'
);
return $result->row();
Its always a good practice to do these kind of stuffs in model page.
I have made few changes on what you have done as follows:
function get_pkg_length_by_id($data)
{
$this->db->where('id', $data['pkg_length_id']);
$query = $this->db->get('pkg_lengths');
/*
Just changed var name from $result to $query
since we have a $result var name as return var
*/
if($result->num_rows() > 0 ) {
$result = $query->row_array();
/*
$result holds the result array.
*/
$result['status'] = array(
'status' => '1',
'status_msg' => 'Record found'
);
//return $result->row();
/*
This will return $result->row() only which
doesn't include your $result['status']
*/
}
else {
$result['status'] = array(
'status' => '0',
'status_msg' => 'cannot find any record.'
);
//return $result->row();
/*
This is not required.
Returning just status message is enough.
*/
}
return $result;
}
I have created a Facebook App that i need people to only enter their data to once.
It's all working and the database is being populated, but i need to make sure people don't keep coming back and re-entering their data endlessly.
What's the best way to check if the user has already submitted their data ?
The signed_request could still have been submitted and their data not entered so i need the check for both to work.
Ideally the PHP would just check for FB ID + other data, and only display a confirmation / thankyou page.
Currently my php to send to the database is:
class Users_Model extends CI_Model {
protected $_name = 'users';
function add($id,$key,$value) {
$data = array(
'id' => $id,
'name' => $key,
'value' => $value
);
return $this->db->insert($this->_name, $data);
}
function update($id,$key,$value) {
$data = array(
'value' => $value
);
$this->db->where(array(
'id' => $id,
'name' => $key
));
return $this->db->update($this->_name, $data);
}
function exists($id,$key=null) {
if($key == null) {
$this->db->where(array(
'id' => $id
));
} else {
$this->db->where(array(
'id' => $id,
'name' => $key
));
}
$query = $this->db->get($this->_name);
if($query->num_rows() > 0) {
return true;
}
return false;
}
function remove($id) {
$data = array(
'id' => $id,
);
return $this->db->delete($this->_name, $data);
}
function all() {
$query = $this->db->get($this->_name);
$results = array();
if($query->num_rows() > 0) {
foreach($query->result() as $row) {
$results[]=$row;
}
}
return $results;
}
}
Any help much appreciated...
What's the best way to check if the user has already submitted their data ?
Check if you already have a record for the user’s Facebook id in your database.