开发者

implement try catch in database class php

this here below is my class database in php

<?php
class DB
{

    private $SQLcommand;
    private $bd;

    public function setSQLcommand($valor)
    {
        $this->SQLcommand = $valor;
    }
    public function getSQLcommand()
    {
        return($this->SQLcommand);
    }

    function __construct()
    {
        $this->bd = new PDO("mysql:host=localhost;dbname=cpd", "root", "");

    }
开发者_JS百科    public function ExecSQL()
    {
        if ($this->SQLcommand != "")
            return($this->bd->exec($this->SQLcommand));
        else
            return(false);
    }   
    public function ExecSelect()
    {
        if ($this->SQLcommand != "")
        {
            $data = $this->bd->query($this->SQLcommand);
            return($data->fetchAll());


        }
        else
            return(false);
    }
    function __destruct()
    {
        $this->bd = null;
    }

}
?>

and here is how I instantiate

include_once 'db_class.php';

$e = new DB();
$e->setSQLcommand("INSERT INTO characteristic (id_charac,name_charac)
                VALUES ('','".$_POST["nomecharac"]."')");
$e->ExecSQL();


$p = new DB();
$p->setSQLcommand("select * from characteristic");                  
$data = $p->ExecSelect();

I would ask where in the code I can I put a try catch, that if an error occurs the try catch redirects to the file maintenance.php, and prevent the bank's User and password are showed...thank you all...


You can put in your constructor __construct()

try {
    $this->bd = new PDO("mysql:host=localhost;dbname=cpd", "root", "");
} catch (PDOException $e) {
    die('Database connection could not be established.');
}


First thing is that I'd use prepared statements; someone can put what they want into $_POST["nomecharac"] that can let them run a command that they want.

As for where to put the try-catch, if you want there to always be a redirect to maintenance.php, put it in the class. Otherwise, put it in the instantiation.

Cheers!


Your Database class should not know that your application has to redirect to a specific page, only that an exception has occurred.

  1. Let Database class throw exceptions.
  2. Catch the exception in your application, and take action.
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜