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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With