简体   繁体   中英

PHP Log to error_log on specific error

I have a query in PHP that is like:

$result = $db->prepare("SELECT * FROM table WHERE page_url_match = :pageurlmatch AND datetime(post_time) > datetime('now', '-32 hours')"); # line 124
$result->bindValue(':pageurlmatch', $shorturl, SQLITE3_TEXT); # line 130

I keep getting an error:

[10-Dec-2015 12:20:09 America/New_York] PHP Warning: SQLite3::prepare(): Unable to prepare statement: 1, near "now": syntax error in XXX on line 124

[10-Dec-2015 12:20:09 America/New_York] PHP Fatal error: Call to a member function bindValue() on a non-object in XXX on line 130

How do I have PHP log a specific variable to the error_log file if this error shows up again. I know i can use error_log($var); but I do not know how to trigger this to only go if there is an error

You start by stop assuming that DB calls will always succeed. In this case, you have an SQL syntax error, meaning the prepare call returned boolean false. You then used that boolean false as if it was a statement handle, and cause further problems.

Never EVER assume success when dealing with external resources. Write defensively: assume failure, test for failure, and treat success as a pleasant surprise.

Guessing that's PDO you're using, so either start testing for boolean false returns, or turn on exceptions and start try/catching everything.

$stmt = $db->prepare(...);
if ($stmt === false) {
   error_log('prepare failed for reason: ' . $db->errorInfo);
   die();
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM