Michael Grigsby
Michael Grigsby

Reputation: 12163

How to test if a CodeIgniter query containing INSERT IGNORE was successful?

In Ci, I've got the following function. How do I test that the query successfully inserted without error's?

public function postToWall() {
    $entryData = $this->input->post('entryData');
    $myChurchId  = $this->session->userdata("myChurchId");
    $this->db->query("INSERT IGNORE INTO wallPosts (entryData, entryCreationDateTime, wpChurchId)
                      VALUES('$entryData', NOW(), '$myChurchId')");
}

Upvotes: 29

Views: 49814

Answers (5)

TV-C-1-5
TV-C-1-5

Reputation: 714

Codeigniter 4:

    $db = db_connect();
     (your insert query)
    return ($db->affectedRows() != 1) ? false : true;

Upvotes: 0

teenage vampire
teenage vampire

Reputation: 359

if you are using bootstrap on codeigniter try flash message or simply redirect

$added = $this->your_modal->function_reference($data);


if ($added) {
    $this->session->set_flashdata('success', 'Added successfully.');
    redirect('home');
} else {
    $this->session->set_flashdata('error', 'Something wrong.');
    redirect('home');

ON CONTROLLER

Upvotes: 1

deya tri
deya tri

Reputation: 53

I prefer use

echo $this->db->affected_rows();

in models file

Upvotes: 0

Nadeem Khan
Nadeem Khan

Reputation: 3434

You can also do it using Transactions like this:

           $this->db->trans_start();
           $this->db->query("INSERT IGNORE INTO wallPosts (entryData, entryCreationDateTime, wpChurchId)
                      VALUES('$entryData', NOW(), '$myChurchId')");
           $this->db->trans_complete();

           if ($this->db->trans_status() === FALSE) {
               return "Query Failed";
           } else {
               // do whatever you want to do on query success
           }

Here's more info on Transactions in CodeIgniter!

Upvotes: 7

Chirag
Chirag

Reputation: 1128

You can use $this->db->affected_rows() function of codeigniter.

See more information here

You can do something like this:

return ($this->db->affected_rows() != 1) ? false : true;

Upvotes: 79

Related Questions