1

I'm getting data back from an AJAX call, which I then try and INSERT into a database. I'm using Silverstripe 3.1 (using DB::query()), but this seems to be a PHP thing.

If the transaction works then everything works as planned, however, if the query fails I get a PHP fatal error.

Basically I'm looking for a way to continue despite a fatal error so that I can throw a failed notification to a user. I'd just like to know if the query worked or not.

*Edit to include Code

$sql = "UPDATE $table SET ,,"; // Syntax error added purposefully
        foreach ($update_array as $key => $value) {
            $name = $formHelpers->some_filter($key);
            $content = $formHelpers->some_filter($value);
            $sql .= " $name='$content',";
        }
        $sql = rtrim($sql, ",");
        $sql .= "WHERE id=$id";

        $result = DB::query($sql);
Turnerj
  • 4,258
  • 5
  • 35
  • 52
Zach Smith
  • 8,458
  • 13
  • 59
  • 133
  • Can you show the bit of your code causing the error? `try catch` maybe all you need – Michael Kunst Aug 25 '15 at 14:55
  • Added a comment. The SQL error is there purposefully to generate an error – Zach Smith Aug 25 '15 at 15:17
  • What is the error message? - there is a difference between straight fatal errors (for example missing T_SOMETHING and the like) and fatal errors because of uncaught Exception – cypherabe Aug 26 '15 at 07:57
  • The error is: "...[25-Aug-2015 16:30:58 Africa/Johannesburg] PHP Fatal error: Couldn't run query: UPDATE form_apas SET ,, profile_corporation_name=..." – Zach Smith Aug 26 '15 at 13:25

1 Answers1

0

I'd need to see your code to tell you exactly what you need to do. However, the concept you are looking for is called try, catch, throw. When you make your database query, add a catch statement. Then if an error is tossed, you can catch it and still do something. Here is a tutorial about Try, Catch, Through in PHP

http://www.w3schools.com/php/php_exception.asp

kayleighsdaddy
  • 670
  • 5
  • 15
  • However, the reason I posted the question is that I saw on stack overflow (http://stackoverflow.com/questions/12928487/php-try-catch-and-fatal-error) that you can only use try-catch blocks to catch exceptions. Not fatal errors.... – Zach Smith Sep 05 '15 at 06:32
  • OK sorry, you are correct that a fatal error is not caught. I just tested it myself. However, if the query fails you should just get zero results. Unless the reason it failed was for a null pointer exception which would cause a fatal error. That can be tested for with if(!DB){Whatever error stuff you want} – kayleighsdaddy Sep 05 '15 at 08:59
  • Not sure why that would happen though, If a correctly formatted query were to run successfully, then the DB connection must be correct. (Is that what you mean by null pointer?) – Zach Smith Sep 06 '15 at 06:22