i am trying to check if an id in the database already exists and if it does not then only insert that id and not the other ones that exist
I have tried to do a where statement that checks if their is a id exists in the database but even if their are new information it does not insert it into the database
Im quite lost here
any guidance would be appreciated
ps i dont want to update a row i want to insert a new updated one that does not exist
$this->db->where('id',$id);
$q = $this->db->get('testing');
if($q)
{
//Do nothing
}
else
{
$this->db->set('id', $id);
$this->db->set('message', $message);
$query= $this->db->insert('testing');
}
Model
<?php
class Fruits_model extends CI_Model
{
function __construct()
{
parent::__construct();
$this->load->database();
}
function check()
{
$query = null; //emptying in case
$id = $_POST['id']; //getting from post value
$name = $_POST['name'];
$query = $this->db->get_where('fruits', array(//making selection
'id' => $id
));
$count = $query->num_rows(); //counting result from query
if ($count === 0) {
$data = array(
'name' => $name,
'id' => $id
);
$this->db->insert('fruits', $data);
}
}
}
?>
You have a logic issue with your code that you need to fix.
In your code, you save the result from your query as $q = $this->db->get('testing'),
and $q will always evaluate to true regardless of the number of rows your return.
You need to check the number of rows using $query->num_rows() > 0 and then the rest
of you code will behave as you expect.
For more details, see: http://ellislab.com/codeigniter/user-guide/database/results.html
$ql = $this->db->select('id')->from('testing')->where('id',$id)->get();
if( $ql->num_rows() > 0 ) {} else {
$a = array('id' => $id, 'message' => $message);
$this->db->insert('testing', $a);
}
This should do it.
You should try like this:
public function record_exists(){
$exists = $this->db->get_where('table_name', array('id' => $id));
if($exists->num_rows() > 0 ){
echo "Some message";
return false;
}else{
// Insert your data into the database...
}
}
You need to select the id's in your MYSQL table with the id you want to check and then count the rows. If the row count is 0 then the id doesn't exist.
$query = mysql_query("SELECT * FROM your_table WHERE id='$id'");
$count = mysql_num_rows($query);
If($count!=0){
// id exists
} else {
// id doesn't exist
}
normally 'id' field is set with auto_increment and set primary which is unique and not repeatable. So there is not problem to worry about existing.
However, in your case I think you are not using it as a 'unique field'.
Let me give you an example.
Here I have a table name 'fruits'
++++++++++++++++++++++++++++++++++++
ငfruit_id | int (primary)
name | text
id | int
++++++++++++++++++++++++++++++++++++++
in your model
function checkId($id)
{
$query=$this->db->get_where('fruits',array('id'=>$id)); //check if 'id' field is existed or not
if($query!=null) // id found stop
{
return FALSE;
}
else // id not found continue..
{
$data = array(
'fruit_id' => $fruit_id ,
'name' => $name ,
'id' => $id
);
$this->db->insert('fruits', $data);
}
}
For Checking An Id Or any column value exist not in database CI have a validation rule for it.
See it live here: Validation Rule
Rule: is_unique
Returns FALSE if the form element is not unique to the table and field name in the parameter. Note: This rule requires Query Builder to be enabled in order to work.
Example: is_unique[table.field]
$this->form_validation->set_rules(
'username', 'Username',
'required|min_length[5]|max_length[12]|is_unique[users.username]',
array(
'required' => 'You have not provided %s.',
'is_unique' => 'This %s already exists.'
)
);
For More Advance use of validation, You can add all validation Setting Rules Using an Array.
$this->form_validation->set_rules(
'username', 'Username',
'required|min_length[5]|max_length[12]|is_unique[users.username]',
array(
'required' => 'You have not provided %s.',
'is_unique' => 'This %s already exists.'
)
);
$config = array(
'your_rule_name' => array(
array(
'username', 'Username',
'required|min_length[5]|max_length[12]|is_unique[users.username]',
array(
'required' => 'You have not provided %s.',
'is_unique' => 'This %s already exists.'
)
)
),
array(
'field' => 'email',
'label' => 'Email',
'rules' => 'required'
)
);
$this->form_validation->set_rules($config);
Related
how can we check firstname and last name is unique validation in cakePHP ?
record1:
first name :raj
last name: kumar
if we enter same name in input field , it should show validation message "Record alredy Exists".
i know how to validate single field validation.
how to validate that the combination of first_name and last_name is unique?
Please help me in this.
Thanks in Advance
You will want to setup a custom validation rule for testing that the 'full name' is unique. For example, in your model add a new method for validation like this:-
public function validateUniqueFullName(array $data) {
$conditions = array(
'first_name' => $this->data[$this->alias]['first_name'],
'last_name' => $this->data[$this->alias]['last_name']
);
if (!empty($this->id)) {
// Make sure we exclude the current record.
$conditions[$this->alias . '.' . $this->primaryKey . ' !='] = $this->id;
}
return $this->find('count', array('conditions' => $conditions)) === 0;
}
Then add the new validation rule to the model's $validate property:-
public $validate = array(
'first_name' => array(
'unique' => array(
'rule' => 'validateUniqueFullName',
'message' => 'Not unique'
)
)
);
Where 'rule' => 'validateUniqueFullName' instructs Cake to use the new validation rule to check that the name is unique.
You'll probably want to tweak/improve the above custom rule to meet your exact requirements but it should put you on the right track.
Try this way
public $validate = array(
'facebook_link' => array(
'rule' => array('customValidation','facebook_link'),
'message' => 'Please enter facebook link.'
),
'twitter_link' => array(
'rule' => array('customValidation','twitter_link'),
'message' => 'Please enter twitter link.'
)
);
function customValidation($data , $filed) {
if(empty($data[$filed])) {
return false;
}
return true;
}
Here is my Rule :
Table Name is : company_info
I have only two fields CompanyID and Telephone
In the update section, i want to check whether the Telephone Number exists for other columns and if the own field have it i don't want to check it. (Currently it checks the own data and returning with Telephone number was taken already).
'Telephone' => 'unique:company_info',
Then i tried with the below rule
But i miss in the
'Telephone' => 'unique|unique:company_info,CompanyID,'.$companyid)
or
'Telephone' => 'unique|unique:company_info,Telephone,'.$companyid)
or
'Telephone' => 'unique|unique:company_info,Telephone,'.$Telephone)
Here is my Code :
$companyid = Input::get('CompanyID');
$Telephone = Input::get('Telephone');
$rule = array(
'Telephone' => 'unique|unique:company_info,CompanyID,'.$companyid
)
$validator = Validator::make($data,$rule);
if ($validator->fails())
{
$messages = $validator->messages();
return "0"."||".$messages = $validator->messages()->first('Telephone');
}
While the update query i need to check for the unique rule except the given id
I refered this one http://laravel.com/docs/4.2/validation#rule-unique
But i am not getting return on $validator = Validator::make($data,$rule);
How can i check for the unique value except the own column
I believe you have the wrong syntax for unique validation
it should be
'Telephone' => 'unique:company_info,CompanyID,'.$companyid
or
'Telephone' => 'required|unique:company_info,CompanyID,'.$companyid
and not
'Telephone' => 'unique|unique:company_info,CompanyID,'.$companyid
Can try this as the Laravel Validation provides us various features
$companyid = Input::get('CompanyID');
$Telephone = Input::get('Telephone');
$data = array('companyid'=>$companyid, 'Telephone'=>$Telephone );
//FOR INSERTING NEW DATA
$rule = array(
'Telephone' => 'required|unique:company_info,Telephone,{:id}'
);
$validator = Validator::make($data,$rule);
//FOR UPDATING AN EXISTING DATA
public static function rule ($id, $merge=[]) {
return array_merge(
[
'Telephone' => 'required|unique:company_info,Telephone,'.$id,
],
$merge);
}
$validator = Validator::make($data,self::rule($id));
Comment for errors...
Try following code
'Telephone' => 'unique:company_info,Telephone,'.$companyid.', CompanyID';
{rule} =>
'unique:{table_name},{unique_column_name},{except_column_value},{except_column_name}'
I have tried almost everything in my knowledge and found on net but nothing works. What I am trying to do is while adding new record I want to check whether the field value is already in database table or not. If not than add else throw error message.
I have tried also with is_usnique but than it is not allowing to modify data since it is considering that form value is exists.
Table name is positions
Coloumn name is position
Input field name is position
I have tried below code in my Controller
public function _unique_poscode()
{
$id = $this->uri->segment(4);
$this->db->where('position', $this->input->post('position'));
!$id || $this->db->where('id !=', $id);
$poses = $this->positions_model->get();
if (count($poses)) {
$this->form_validation->set_message('_unique_poscode', '%s should be uinique');
return FALSE;
}
return TRUE;
}
And set rules in my Model as below
public $rules = array(
'position' => array(
'field' => 'position',
'label' => 'Position Code',
'rules' => 'trim|required|max_length[10]|callback__unique_poscode|xss_clean'
),
'label' => array(
'field' => 'label',
'label' => 'Position Label',
'rules' => 'trim|required|max_length[50]|xss_clean'
),
);
but no matter whatever I do it is not working and adding record even if it is exists in table.
Can anyone help me to fix this issue? Thanks a lot.
you are missing parameter
public function _unique_poscode( $p )
{
$this->form_validation->set_message('_unique_poscode', '%s should be uinique');
$q = $this->db->get_where('positions', array('position' => $p));
return ($q->num_rows() > 0) ? TRUE : FALSE;
}
and in rules
...|callback__unique_poscode|trim
and how it is done by codeigniter is as one of rules, please see this for more
is_unique[table.column]
Simply add this to rules and check.
is_unique[TABLENAME.COLUMNNAME]
According to your one it should be,
is_unique[positions.position]
I am using 3 tables for joining.
I have a form where i can add a factory. I also can choose a category for that specific factory.
i use the following tables:
factorycategories
-----------------
idfactorycategories
idfactories
idcategories
(in this table i use a join to show the categories and factories on one page)
factories
---------
idfactories
factoryname
address
country
telephone
...
...
categories
----------
idcategories
category
I want to insert the last inserted idcategories and idfactories in my factorycategories table.
How can i do this?
My model for inserting the form values:
function addbedrijf()
{
$data1 = array(
'Bedrijfsnaam' => $this->input->post('Bedrijfsnaam'),
'Postcode' => $this->input->post('Postcode'),
'Plaats' => $this->input->post('Plaats'),
'Telefoonnummer' => $this->input->post('Telefoonnummer'),
'Email' => $this->input->post('Email'),
'Website' => $this->input->post('Website'),
'Profiel' => $this->input->post('Profiel'),
'Adres' => $this->input->post('Adres'),
'logo' => $this->input->post('logo')
);
$this->db->insert('bedrijven', $data1);
}
My model function for showing categories and factories on the same page:
function get_result($idbedrijven)
{
$this->db->where('bedrijven.idbedrijven', $idbedrijven);
$this->db->join('bedrijven', 'bedrijfcategorieen.idbedrijven = bedrijven.idbedrijven');
$this->db->join('categorieen', 'bedrijfcategorieen.idcategorieen = categorieen.idcategorieen');
$this->db->group_by('Categorie', 'idbedrijven', 'idcategorieen');
$result = $this->db->get('bedrijfcategorieen', 1);
return $result->result();
}
Hope i provided enough code for you guys.
Edit:
the code that i have so far using the example below:
function addbedrijf()
{
$data1 = array(
'Bedrijfsnaam' => $this->input->post('Bedrijfsnaam'),
'Postcode' => $this->input->post('Postcode'),
'Plaats' => $this->input->post('Plaats'),
'Telefoonnummer' => $this->input->post('Telefoonnummer'),
'Email' => $this->input->post('Email'),
'Website' => $this->input->post('Website'),
'Profiel' => $this->input->post('Profiel'),
'Adres' => $this->input->post('Adres'),
'logo' => $this->input->post('logo')
);
$this->db->insert('bedrijven',$data1);
if($this->db->affected_rows() >= 1)
{
$this->insert_bedrijfcat($this->db->insert_id);
}else{
return FALSE
}
}
function insert_bedrijfcat($id)
{
$this->db->insert('bedrijfcategorieen',array('idbedrijven'=>$id));
return $this->db->affected_rows() ?= 1 ? TRUE : FALSE;
}
You are inserting data to the bedrijven table
and you want to get the last inserted id of
categories and factories table then insert it to factorycategories table also?
THe question is when inserting data to bedrijven table do you insert data to the
categories and factories table ? Because if you do you can use $this->db->insert_id to get the last input id of your categories and factories table, if not you need to query a different sql to get both last input id.
EDIT
here so i modified a some code example
class Some_model Extends CI_Model
{
public function insert_factory($data)
{
$this->db->insert('factory_table',$data);
//if has affected rows
if($this->db->affected_rows() >= 1)
{
// the insert was successfull send the last insert id to another method
$this->insert_to_factorycateg($this->db->insert_id);
}else{
return FALSE
}
}
//method to insert to factorycateg
public function insert_to_factorycateg($id)
{
//insert
$this->db->insert('factorycategories',array('factoryid'=>$id));
//if affected rows return true else false
return $this->db->affected_rows() >= 1 ? TRUE : FALSE;
}
}
I've go some validation functions written to check if the user's email exists in the system.
I am getting the following error
Notice (8): Undefined offset: 0 [CORE/cake/libs/model/model.php, line 1122]
This is the code which causes the error
'email' => array(
'emailRule-1' => array(
'rule' => 'email',
'message' => 'email format is incorrect',
'last' => true
),
'emailRule-2' => array(
'rule' => 'checkEmailExist',
'message' => 'email already exists in the system'
)
),
And rule2 seems to be responsible for the error, and here is the rule2:
function checkEmailExist($emailAddress, $user_id){
$this->recursive = -1;
if($user_id > 0){
$user = $this->read(array('email'), $user_id);
if($emailAddress == $user['User']['email'])
return true;
}
$result = $this->find('count', array('conditions' => array('User.email' => $emailAddress)));
return $result > 0 ? false : true;
}
Why not do it like this?
public $validate = array(
'email' => array(
'rule' => array('email', 'isUnique')
)
);
You might want to split it up into two separate rules to apply your own error messages, but this should work just fine.
Did you try to debug what $emailAddress contains?
I bet this is an array^^
function checkEmailExist($emailAddress, $user_id){
$this->recursive = -1;
$email = array_shift(emailAddress);
...
you need to get the child element first
so remember: always a good idea to use debug() or pr() to debug your variables first.