There is no best way, what exists is the way that most meets your purpose, in the case below, is a simple example, using PDO:
class Database {
private static $servidor = 'localhost'; // Servidor, no caso poderia ser também localhost
private static $usuario = 'root'; // usuário do banco de dados
private static $senha = 'senha'; // senha do banco de dados
private static $banco = 'banco'; // nome do banco de dados
private static $instance = null;
public static function getConnection() {
if (!self::$instance instanceof PDO) {
try {
self::$instance = new PDO('mysql:host=' .
self::$servidor . ';dbname=' .
self::$banco,
self::$usuario,
self::$senha);
} catch (PDOException $exc) {
echo "Erro ao conectar :: {$exc->getMessage()}";
}
}
return self::$instance;
}
public function fetchAll($query) {
$con = self::getConnection();
$stmt = $con->prepare($query);
$this->execute($stmt);
if ($stmt->rowCount()) {
return $stmt->fetchAll(PDO::FETCH_OBJ);
} else {
return false;
}
}
public function execute(PDOStatement $stmt, array $data = null) {
try {
if (isset($data)) {
$stmt->execute($data);
} else {
$stmt->execute();
}
} catch (PDOException $exc) {
echo $exc->getTraceAsString();
}
}
public function action($sql, array $data) {
$con = self::getConnection();
$stmt = $con->prepare($sql);
$this->execute($stmt, $data);
if ($stmt->rowCount()) {
return true;
} else {
return false;
}
}
}
$conexao = new Database();
//listando...
$collection = $conexao->fetchAll("SELECT * FROM tabela");
foreach ($collection as $data) {
echo $data['campo'] . '<br>';
}
//deletando...
$deletou = $conexao->action('DELETE FROM tabela WHERE id=:id',array('id' => (int) $id));
if ($deletou) {
echo "apagou!";
}
//inserindo
$insert = $conexao->action("INSERT INTO tabela (campo1, campo2) values (:campo1,:campo2)",array('campo1'=>'valor1','campo2'=>'valor2'));
if ($insert) {
echo "gravou!";
}
//atualizando
$update = $conexao->action("UPDATE tabela SET campo1=:campo1, campo2=:campo2 where id=:id",array('campo1'=>'valor1','campo2'=>'valor2','id' => (int) $id));
if ($update) {
echo "atualizou!";
}
Read this before you want to know which is the best way: Why should we not use mysql type functions_*?
– Ivan Ferrer