1

I use CodeIgniter as my web application framework. I used a simple Try/Catch and I sent a sample value to test it, and it failed!

I know I can use $this->db->escape() function to solve my data problem but I just want to know: Why TRY/CATCH can not catch this error!

Controler code:

    $this->load->model('user_model');
    $result = $this->user_model->test_user("tes'ti");

Model code:

function test_user($username){
    try {
        $query_str = "SELECT * FROM tbl_user WHERE username = '".$username."'";
        $result = $this->db->query($query_str);
        return $result;

    } catch (Exception $e) {
        return;

    }
}

Output:

A Database Error Occurred

Error Number: 1064

You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'ti'' at line 1

SELECT * FROM tbl_user WHERE username = 'tes'ti'

Let me know, where I made a mistake, if I did!

Cœur
  • 37,241
  • 25
  • 195
  • 267
Mona
  • 788
  • 3
  • 13
  • 18

5 Answers5

2

You need to throw an exception if there was some mysql error:

try {
    $query_str = "SELECT * FROM tbl_user WHERE username = '".$username."'";
    $result = $this->db->query($query_str);

    if (!$result)
    {
      throw new Exception('error in query');
      return false;
    }        

    return $result;

} catch (Exception $e) {
    return;
}
Sarfraz
  • 377,238
  • 77
  • 533
  • 578
  • Thanks Sarfraz, I did your recommendations but it failed again! do you have more ideas?! – Mona Aug 05 '10 at 19:26
  • 1
    @Monica: Then i am pretty much sure it is handled/done so by the `query` function `$this->db->query`. If you try the same code with simple `mysql_query` command for example in a test page, it should catch it. – Sarfraz Aug 05 '10 at 19:48
  • @Sarfraz: WOW! So it's because I use CodeIgniter?! Are you sure?! So I must google about CodeIgniter Database Error Handling problem! Is it true?! – Mona Aug 05 '10 at 19:55
  • @Monica: Look possibly the `query` function either returns the result or outputs the result by throwing an exception or using `mysql_error()` function, you might want to check that to confirm it just in case. – Sarfraz Aug 05 '10 at 20:07
  • 2
    @Sarfraz: You help me to find the source of problem and the way to solve it! I found that the CI Database class contained its error handling part and it doesn't throw any exception at all! I turned it off (if anybody want to know, do this: in config/database.php -> $db['default']['db_debug'] = FALSE;) .... My TRY/CATCH works properly now. Thank you really much ;) – Mona Aug 05 '10 at 20:29
  • Thanks [Monica](http://stackoverflow.com/users/399417/monica). Your comment helped me solve my problem. whole day i was scratching my head. Then i switched of the debug has u told. thank you. – Jeeva Dec 22 '16 at 10:51
1

@Monica, not sure if this helps, but you should know that the CI database functions never throw any errors. They just return true or false. Therefore @Sarfraz is right, you must either check for true/false yourself and/or throw Exceptions yourself.

Also, your exception handling code does nothing. This means it will continue running any scripts coming after it, including scripts that work with the recordset that just failed.

Fer
  • 4,116
  • 16
  • 59
  • 102
  • @Fredy, do you mean even when I set "$db['default']['db_debug'] = FALSE" it does not throw any exception?! ... And about that code, you're right but that was just a sample to show my problem! :P – Mona Aug 27 '10 at 01:49
  • @Monica. Yes, that is correct. No CI db code will EVER throw an error. It will only return true or false, after which you must throw and/or catch an error. – Fer Aug 30 '10 at 19:31
1

Instead of getting code igniter db errormsg (html), i wanted to get a json display, then inside the ajax request i just check for success

I rewrote the DB_driver.php in the

function display_error($error = '', $swap = '', $native = FALSE)


//commented
//echo $error->show_error($heading, $message, 'error_db');

//this is the magic
$data['success'] = false;
$data['heading'] = $heading;
$data['message'] = $message;
$data['type'] = 'error_db';

echo json_encode($data);
exit;

this will create a json with success value as false

then i just check for false...

Works for all my ajax request .... just and idea ...

Acidfilez
  • 46
  • 1
0

The reason you are getting an error is due to 'tes**'ti' the **'. use '$username."'".$username1

Where $username = 'tes'
and $username1 = 'ti
X10nD
  • 21,638
  • 45
  • 111
  • 152
  • Thanks jean, but it's not my problem... I just want to fix my try/catch problem... actually you can do a search with this word "tes'ti", you must use addslashes() in php or escape() in CI... ;) – Mona Aug 05 '10 at 19:32
  • @monica The error triggers in your query statement. I have never used try and catch, actually never found the need to be honest. – X10nD Aug 05 '10 at 19:43
  • @Jean: I read your comment again, and now I get your mean! :D thanks – Mona Aug 05 '10 at 23:08
  • @monica I never found the need to put in try/catch – X10nD Aug 06 '10 at 07:49
  • @Jean I don't want to show SQL Script Error to end users, indeed CI shows any database exception completely in its format! I want to show a simple error, not a detail error about my database! So I need to manage it myself. :P – Mona Aug 06 '10 at 17:45
  • @monica, the script will not show an error, unless the variables passed is incorrect, check variables before passing – X10nD Aug 06 '10 at 18:43
0

For me, the code by @Sarfraz did not work, at least in CI 3.1.5 the problem was that $this->db->query has a bunch of wrapping functions that immediately call the error handlers built into code igniter. If you want to throw a new RuntimeException, then use $this->db->simple_query method instead.

on an aside the OP should consider the active records, something like:

$result = $this->db->select()
    ->from('tbl_user')
    ->where('username',$username)
    ->get()
    ->result();

should get around these problems because codeigniter active record framework should escape the queries for you.

pgee70
  • 3,707
  • 4
  • 35
  • 41