Below I'll give you an example of how I use the PDO connection today to access my databases. I would like to see with you, whether it is a good practice this way, or whether it is recommended a safer and more efficient way.
For example:
<?php
require "environment.php";
global $pdo;
$config = array();
$config['options'] = array(PDO::MYSQL_ATTR_INIT_COMMAND => "SET NAMES
UTF8");
if(ENVIRONMENT == "DEVELOPTMENT"){
$config['dbname'] = '';
$config['host'] = '';
$config['user'] = '';
$config['password'] = '';
} ELSE IF(ENVIRONMENT == "PRODUCTION"){
$config['dbname'] = '';
$config['host'] = '';
$config['user'] = '';
$config['password'] = '';
}
try{
$pdo = new PDO("mysql:dbname=".$config['dbname'].";
host=".$config['host'], $config['user'], $config['password'],
$config['options']);
}catch(PDOExcepetion $e){
echo "ERRO: ".$e->getMessage();
exit;
}
In the class I use this way:
<?php
class Categorias{
public function getListaCategorias(){
$array = array();
global $pdo;
$sql = $pdo->query("Select * from categorias");
if($sql->rowCount() > 0){
$array = $sql->fetchAll();
}
return $array;
}
}