Welcome Guest, Not a member yet? Register   Sign In
form_validation, make sure it exists in database
#1

[eluser]RandyCram[/eluser]
Alright, I searched the forums a little bit but did not see anything like it so i decided to post it.

This is a simple addition to form_validation that checks to make sure that something exists in the database.

Example: if you have a login system, instead of creating a function or something in the model you can just run this and it will check to see if it is a valid login name.

Code:
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');

class MY_Form_validation extends CI_Form_validation {

/**
  * Exists
  * check to make sure something exists in database
  *
  * @access public
  * @param string
  * @return bool
  */
public function exists($value, $params) {

  $CI =& get_instance();
  $CI->load->database();

  $CI->form_validation->set_message('exists',
   'The %s does not exist in the database');

  list($table, $field) = explode(".", $params, 2);

  $query = $CI->db->select($field)->from($table)
   ->where($field, $value)->limit(1)->get();

  if ($query->row()) {
   return true;
  } else {
   return false;
  }

}
}

basically all i did was was modify the function name and the way it returns from the "unique" function that you can find all over the place, so you use it in the same fashion.

Code:
exists[database_table.row_name]

better example in use:
Code:
exists[users.email_address]
this would be good if you have the user entering an email address and want to make sure there is a user in your database table called "users" with that email address.

I hope this helps somebody.




Theme © iAndrew 2016 - Forum software by © MyBB