我有一个应该引发异常的函数,但是它暂停了脚本的执行: 注意: *我有意传递错误的查询来测试功能行为。 config.php
<?php
// Database settings
$host = '127.0.0.1'; // The host of MySql
$db_name = 'db_stocks'; // Database name
$user = 'root'; // Database User name
$pass = ''; // Database password
$port = 3300;
$charset = 'utf8';
$dsn = "mysql:host=$host;port=$port;dbname=$db_name;charset=$charset";
$options = [
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,
PDO::ATTR_EMULATE_PREPARES => false,
];
try {
$pdo_ms3 = new PDO($dsn, $user, $pass, $options);
} catch (\PDOException $e) {
throw new \PDOException($e->getMessage(), (int)$e->getCode());
}
?>
此脚本:
$query_name = 'mistyped sql';
$query_file = 'SELECT * FROM stock--';
echo count( query_loader( $query_name, $query_file, $pdo_ms3 ) );
function query_loader( $query_name, $query_sql, $pdo ) {
try {
$stmt = $pdo->prepare( $query_sql );
if( !$stmt )
throw new PDOException( 'query failed to parse' );
$stmt->execute( );
return $stmt->fetchAll();
var_dump( $stmt->errorInfo() );
}
catch( PDOException $e ) {
log_error( $query_name, $query_sql, $e->getMessage() );
return -1;
}
}
function log_error( $query_name, $query_sql, $exception_msg ) {
global $log_error;
$error_msg['date'] = date( 'd-m-Y h:i', time() );
$error_msg['query_name'] = $query_name;
$error_msg['query_sql'] = $query_sql;
$error_msg['exception_msg'] = $exception_msg;
$error_msg = json_encode( $error_msg ) . "\n";
$handle = fopen( $log_error, 'w+');
fwrite( $handle, $error_msg );
fclose( $handle );
}
?>
即使return
之后紧接着if( !$stmt )
,也总是出现相同的错误。
致命错误:在第12行的C:\ Program Files(x86)\ WebDevServer \ data \ localweb \ listk.php中的非对象上调用成员函数prepare()