For the last few day I tried to figure out how to work with MySQL and PDO. Although I've tried to read a lot about the subject, there are still a lot of things I don't understand.
Because of this lack of knowledge, I can't really judge this code (or other example code on-line) on its safety and logic, and therefore was hoping I could get some feedback on it.
The class makes a connection and returns a query:
class Connection
{
private $username = "xxxx";
private $password = "xxxx";
private $dsn = "mysql:host=host;dbname=name_db";
private $sql;
private $DBH;
function setSQL($sql){
$this->sql = $sql; //if $sql is not set it troughs an error at PDOException
}
public function query()
{
//the connection will get established here if it hasn't been already
if (is_null($this->DBH))
try {
$this->DBH = new PDO( $this->dsn, $this->username, $this->password );
$this->DBH->setAttribute( PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION );
//query
$result = $this->DBH->prepare($this->sql);
$result->execute();
return $result->fetch(PDO::FETCH_ASSOC);
} catch(PDOException $e) {
echo "I'm afraid I can't do that1.";
//file_put_contents('PDOErrors.txt', $e->getMessage(), FILE_APPEND);
}
}
//clear connection and variables
function __destruct(){
$this->DBH = null;
}
}
Using the class:
$sql = "SELECT * from stock WHERE id = 302";
$test = new Connection();
$test->setSQL($sql);
echo $test->query();