need to add form validation codeigniter - php

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

Related

Code igniter Session is not storing data, it only saves the Email which we are entering in input box at login-form?

Code-igniter Session is not storing data, it only saves the Email which we are entering in input box in login-form. I set this $config['sess_use_database'] = TRUE; and created a ci_sessions table also in DB but no sake. I tried this on both versions on code-igniters(2 & 3) Please help me to sort out this problem. Thank you. This is my code. First one is controller and the second one is model.
public function validate_credentials()
{
$this->load->model('passenger_login_model');
$query = $this->passenger_login_model->validate();
if($query)
{
$data = array(
'Email' => $this->input->post('Email'),
'is_logged_in' => true,
'P_ID' => $query->P_ID,
'CNIC' => $query->CNIC
);
$this->session->set_userdata($data);
echo $this->session->userdata('Email');
echo $this->session->userdata('P_ID');
//redirect('front');
}
else
{
echo "<script>alert('Incorrect Email or Password!');</script>";
$this->index();
}
}
and as output, it only shows me the user#user.com not P_ID
and this is model
class Passenger_Login_model extends CI_Model
{
/*`passenger`(`P_ID`, `Name`, `Image`, `CNIC`, `Passport_No`, `Gender`, `Email`,
`Password`, `Phone_No`, `Mob_No`, `Address_1`, `Address_2`, `Date` */
function validate()
{
$data=array(
'Email' =>$this->input->post('Email'),
'Password' =>$this->input->post('Password')
);
$rec=$this->db->get_where('passenger', $data)->result();
$c = count($rec);
if($c>0)
{
return true;
}
else
{
return false;
}
}
function is_logged_in()
{
$this->load->library('session');
$is_logged_in = $this->session->userdata('is_logged_in');
if(!isset($is_logged_in) || $is_logged_in != true)
{
echo 'You don\'t have permission to access this page.'.anchor('login',"Login");
die();
}
}}
You should return the data fetch from your model query, use fetch function to do that, for more reference click, So your model validate function should be
function validate()
{
$data=array(
'Email' =>$this->input->post('Email'),
'Password' =>$this->input->post('Password')
);
$rec=$this->db->get_where('passenger', $data);
return $rec->result_array(); // returns data as array // might help you
}
return $res->result_array(); will return multipdimentional array of data from db, to know more about result_array() check this
Session issue is from your controller function the result is array now.
public function validate_credentials()
{
$this->load->model('passenger_login_model');
$result_data = $this->passenger_login_model->validate();
// result data is array now
if(is_array($result_data) && count($result_data) > 0)
{
// var_dump($result_data); // check this var_dump you will get multidimensional array
$data = array(
'Email' => $this->input->post('Email'),
'is_logged_in' => true,
'P_ID' => $result_data[0]['P_ID'],
'CNIC' => $result_data[0]['CNIC']
);
$this->session->set_userdata($data);
echo $this->session->userdata('Email');
echo $this->session->userdata('P_ID');
//redirect('front');
}
else
{
echo "<script>alert('Incorrect Email or Password!');</script>";
$this->index();
}
}
Hope this help, Happy coding.
My problem solved, i just updated the model to this...
function validate()
{
$data=array(
'Email' =>$this->input->post('Email'),
'Password' =>$this->input->post('Password')
);
$query = $this->db->get('passenger');
if ($query->num_rows())
{
return $query->row();
}
}

Using flashdata to determine if model was successful in CodeIgniter

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.

if else is not working

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.

Where to pass back message when Model cannot find a record in DB in MVC?

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;
}

How can i run a check on a MySQL database for a FB ID, & other personal data so only a certain page is shown when revisiting?

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.

Categories