在生产环境中处理预准备语句时出错

时间:2015-12-04 15:24:32

标签: php mysqli prepared-statement

在生产环境中,当使用预准备语句并完成所有其他验证时,我是否需要在每个步骤中进行错误检查,或者我可以只检查$stmt的最终结果是真还是假?

我正在尝试清理大约2000行的函数文件,并且当已经进行了如此多的验证(即检查空值,所需值,空字段等)时,其中很多只是浪费空间。 / p>

这是一个粗略的,非常简单的例子,我想做什么。

$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';
}

编辑:我可能应该提到先前已经检查过的$conn

1 个答案:

答案 0 :(得分:0)

你必须决定你的情况是否必要。但是一些程序员会说,捕获错误的代码几乎与普通代码非常相似。

简而言之:如果可能出现错误 CATCH IT ;)

否则我建议您为数据库功能创建一个Wrapper类。

只是一个小例子,指出你正确的方向:

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 

注意:这不是一个有效的例子,我建议使用一个好的框架或一个小的包装类