How to check if id already exists - codeigniter
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