Displaying WPDB error in try catch not working? - php

I am trying to create a Class that will be using a external api and wpdb class however i am having issues already in the try catch block please confirm the below is correct:
<?php
require_once( $_SERVER['DOCUMENT_ROOT'] . '/wp-config.php' );
require_once( $_SERVER['DOCUMENT_ROOT'] . '/wp-includes/wp-db.php' );
class LoLApi
{
private $database;
public function __construct()
{
try {
$this->database = new wpdb('user', 'pass', 'table', '127.0.0.1');
$this->database->show_errors();
} catch (Exception $e) {
return $e->getMessage();
}
}
}
?>
in the other page:
<?php
session_start();
require 'includes/lolapi.class.php';
$api = new LoLApi;
exit();
?>

You should be checking instead whether it returns a WP_Error object. If the WP_Error class doesn't exist it will just die and dump an error message. Nowhere does it actually throw an exception.
If you include wp-load.php you'll have the WP_Error class available and you can check for it in the data returned. You could also extend the wpdb class and override the db_connect method to throw a proper exception instead of killing the script on a connection failure.

Related

PHP Correct way to call mysqli using Intelephense

This code triggers my editor's intelephense for error:
/**
* Connect to database
*/
public function link() {
global $config; mysqli_report(MYSQLI_REPORT_ERROR);
try {
return new \mysqli($config['db_hostname'], $config['db_username'], $config['db_password'], $config['db_name']);
} catch (\exception $e) {
throw new \exception($e->getMessage(), $e->getCode());
}
}
Expected 6 arguments. Found 4.intelephense(10005)
would it be fine if I just use:
return new \mysqli($config['db_hostname'], $config['db_username'], $config['db_password'], $config['db_name'],null,null);
Thank you all for answering; also deceze who corrected me on wrong way to catch exception;
this is edited code:
/**
* Connect to database
*/
public function link() {
global $config; mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
try {
return new \mysqli($config['db_hostname'], $config['db_username'], $config['db_password'], $config['db_name'], ini_get('mysqli.default_port'), ini_get('mysqli.default_socket'));
} catch (\exception $e) {
echo 'Cannot connect to a database server'; die();
}
}
note ,this is for withing the class using namespaces...
The intelephense plugin uses the stubs from PhpStorm. The author already submitted a PR to fix this (and other functions with optional parameters): https://github.com/JetBrains/phpstorm-stubs/pull/520.
As soon as that's merged and the stubs are updated, you should no longer receive the problem reported in vscode.
There should be no need to change your constructor call, it is valid code and will execute without problems.

Using Exceptions to control application flow

I am currently writing a web app in PHP and have decided to use exceptions (duh!).
I could not find an answer to whether putting try and catch blocks in all functions would be considered bad code.
I am currently using Exceptions to handle Database errors (Application errors are handled via a simple function which just adds them to an array and then they are displayed to the user). The try blocks are placed on all functions which require a database connection.
The code in question is:
public function db_conn_verify()
{
if(!isset($this->_mysqli)){
throw new Exception("Network Error: Database connection could not be established.");
} else {
return Null;
}
}
And an example function using this code:
public function get_users() {
try {
$this->db_conn_verify();
//Rest of function code
return True;
} Catch(Exception $e) {
Core::system_error('function get_users()', $e->getMessage());
return False;
}
}
Also would it be better to extend the Exception class and then use that new Exception class to handle application errors?
Thanks
I suggest to you to use something like this:
public function get_users() {
try {
if( !isset($this->_mysqli) ) {
throw new Exception("Network Error: Database connection could not be established.");
}
//Rest of function code
} Catch(Exception $e) {
Core::system_error('function get_users()', $e->getMessage());
}
}
I prefer to use my exends of Exception, but is the same. For exdending exception you can see the PHP documentation to Example #5
EDIT: For an immediate use of try-catch on database connection error you can try this:
try{
$mysqli = new mysqli("localhost", "user", "password", "database");
if ($mysqli->connect_errno) {
throw new Exception("Network Error: Database connection could not be established.");
}
} Catch(Exception $e) {
Core::system_error('function get_users()', $e->getMessage());
}

can't figure what might causing this error when creating PDO object

i am following a tutorial to create an OOP based login system.I did everything accordingly but while creating pdo i am getting an error in DB.php file in line 15.Can't figure out the reason for this error.Been stuck there for some time.Can anyone help me out with this error .The code might look long but it is a piece of cake for you i promise.There are FOUR php files.
1.init.php file holds the ingredients to create a new PDO() object.
2.config.php file is used to get data from init.php file as string is passed to it as ('mysql/host') type and use explode() function to extract data from it.
2.DB.php file is used to connect to database.
The error i am getting is
DB.php file:
class DB{
private $_instance=null;
private $pdo,
$query,
$error=false,
$results,
$count=0;
private function __construct(){
try{
$this->$pdo=new PDO('mysql:host='.Config::get('mysql/host').';dbname='.Config::get('mysql/db'),Config::get('mysql/user'),Config::get('mysql/password'));
}catch(PDOException as $e){
echo $e->getMessage();
}
}
public static function getInstance(){
if(!isset(self::$_instance)){
self::$_instance=new DB();
}
return self::$_instance;
}
}
Config.php file:
class Config{
public static function get($path){
if($path){
$config=$GLOBALS['config'];
$arr=explode('/',$path);
foreach($arr as $bit){
if(isset($config[$bit])){
$config=$config[$bit];
}
}
return $config;
}
}
}
init.php file:
session_start();
$GLOBALS['config']=array(
'mysql'=>array(
'host' => 'localhost',
'db' => 'login',
'user' => 'root',
'password' => ''
)
);
spl_autoload_register(function($class){
require_once 'c:/xampp/htdocs/login/classes/'.$class.'.php';
});
require_once 'c:/xampp/htdocs/login/function/sanitize.php';
index.php file:
require_once 'c:/xampp/htdocs/login/core/init.php';
DB::getInstance()->query('SELECT name FROM table WHERE id=1');
Your error message is a Parse Error. This means the PHP interpreter/processor/program tried to read your file, but found a syntax error, and had to stop. If you look at Line 15 of DB.php (per the error message)
}catch(PDOException as $e){
You'll see the problem. This isn't valid PHP syntax -- you probably want
}catch(PDOException $e){
The PDOException bit of that is a a class type hint for the exception handling code -- there's no need to use the as.

PDO "exception safety" and writing it to a log file PHP

I am writing a PDO wrapper and having this issue with catching exceptions.
I am trying to maintain exception safety practice,so I wanted to know how to catch an exception,writing it to a log file,and using exception safety to to do something, probably tell the user to retry action again or navigate to an error page or whatever (anything you can suggest).
So how is it done if possible?
Look at this code snippet, it shows how it is done:
class MyDb extends PDO
{
protected $error;
function __construct( $logger )
{
try {
parent::__construct( 'mysql:host=localhost;dbname=xxxx', 'xxx', 'xxx' );
$this->setAttribute( PDO::ATTR_EMULATE_PREPARES, false );
}
catch ( Exception $e ) {
$this->error = $e->getMessage();
// do your log writing stuff here
$logger->Add( $this->error );
}
}
}
update:
usage of the class:
$logger = new MyLogger();
$db = new MyDb( $logger );
of course, you need a logger class with a add method:
class MyLogger
{
const FILENAME = '/tmp/mylog.txt' ;
function Add( $error )
{
file_put_contents( self::FILENAME, $error, FILE_APPEND);
}
}

PHP SQLite3 error?

How do I know if there's an error if I did $db = new SQLite3("somedb.db"); in PHP? Right now the $db doesn't really give me any sort of error?
I can check for file existance, but I'm unsure if there could be any other errors when I open a connection.
You should enable exceptions and instantiate in a try-catch block.
It is not obvious from the documentation but if you use the constructor to open the database it will throw an exception on error.
Further if you set the flag SQLITE3_OPEN_READWRITE in the second argument then it will also throw an exception when the database does not exist (rather than creating it).
class Database extends SQLite3
{
function __construct($dbName)
{
$this->enableExceptions(true);
try
{
parent::__construct($dbName, SQLITE3_OPEN_READWRITE );
}
catch(Exception $ex) { die( $ex->getMessage() ); }
}
Try:
echo $db->lastErrorMsg();

Categories