Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

}
like image 641
Hashey100 Avatar asked Apr 20 '13 21:04

Hashey100


2 Answers

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

?>
like image 71
Wayne Tun Avatar answered Nov 15 '22 21:11

Wayne Tun


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

like image 29
Marc Audet Avatar answered Nov 15 '22 23:11

Marc Audet