Error handling prepared statements in a production environment

In a production environment when using prepared statements and all other validation is done, do I need to error check every every step of the way or can I just check end result of $stmt for true or false?

I am trying to clean up about 2000 lines of a function file and a lot of it just seems like wasted space when there is so much validation already done(ie checking for empty values, required values, empty fields etc).

Here is a rough, extremely simple, example of what I would like to do.

$sql = "SELECT count(*) FROM foo WHERE somecol = ?";

$stmt = $conn->prepare($sql);
$stmt->bind_param("s",$value);
$stmt->execute();

$stmt->bind_result($c);
$stmt->fetch();

if(false === $stmt){
    //My error report
    trigger_error("Something bad happened!" );
    //Error user sees
    $userErrorMsg[] 'Some generic msg here';
}

EDIT: I probably should have mention the $conn has been checked previously.

Answers


You have to decide if it's necessary in your case or not. But some programmers would say, that the code to catch an error is almost that much like the normal code.

In short: If there can be an error CATCH IT ;)

Otherwise I would recommend you to create a Wrapper class for your DB functions.

Just a small example to point you in the right direction:

class MyDBClass {
    private static $con = null;
    private static $instance = null;

    public static function getInstance() {
        if( null === self::$instance) {
            // add error handling ;)
            self::$instance = new MyDBClass();
            self::$instance->setConnection();
        }

        return self::$instance;
    }

    private function setConnection() {
        if( null === self::$con) {
            // add error handling ;)
            self::$con = mysqli_connect("localhost","my_user","my_password","my_db");
        }
    }

    private function __construct() {}

    public function select( $tableName, $columns = "*", $conditions = array(), $numRows = null ) {
        // add your stuff with error handling
    }

    public function selectRow( $tableName, $columns = "*" , $conditions = array() ) {
        // add your stuff with error handling
    }
}

// use of class
$db = MyDBClass::getInstance();
$db->select( "mytable" );// would (for example) select * from mytable 

NOTE: This is not a working example and I would recommend to get use a good framework or a small wrapper class


Need Your Help

Display an image using the path of the image

c++ xcode image path system

I used this code below to pop an image for me but it's not working, so what is wrong with the view function?

what does the colon mean in the Twitter API Resource URL format?

api url twitter

The Twitter API for retweeting shows as the Resource URL the following: