简体   繁体   中英

How to check if id already exists - codeigniter

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

?>
$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 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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM