2

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", "");

    }
    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...

0

3 Answers 3

2

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.');
}
Sign up to request clarification or add additional context in comments.

Comments

2

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!

2 Comments

Good answer, especially with the prepared statements +1
could you illustrate for me ? i'll be very grateful if you did
1

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.

1 Comment

could you illustrate for me ? i'll be very grateful if you did

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.