How to test if Ci successfully inserted data
Asked Answered
S

5

29

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')");
}
Silassilastic answered 15/3, 2012 at 22:39 Comment(0)
L
79

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;
Listless answered 15/3, 2012 at 23:14 Comment(1)
Or simply: return $this->db->affected_rows() > 0;Marcellamarcelle
S
7

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!

Spherics answered 27/9, 2016 at 16:14 Comment(0)
I
1

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

Isobar answered 12/3, 2020 at 8:15 Comment(0)
K
0

I prefer use

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

in models file

Klaraklarika answered 11/3, 2020 at 21:20 Comment(0)
A
0

Codeigniter 4:

    $db = db_connect();
     (your insert query)
    return ($db->affectedRows() != 1) ? false : true;
Aureolin answered 13/3, 2023 at 0:26 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.