To make a encapsulation, I prefer to use 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!";
}
Yes it is possible, what error happens?
– rray
The first argument of
mysqli_query()
is the connection apparently why it doesn’t work.– rray
Try it like this
$delete = mysqli_query($conexao, "TRUNCATE table sap_reportes.zempe019") or die(mysqli_error($conexao));
– rray
Did a mistake appear?
– rray
A delete without Where works?
– rray
Have any error being returned you need to discover it or try to run this query directly in the bank see via phpmyadmin or Workbench
– rray
Yes, any type of encapsulation is possible.
– Ivan Ferrer
can solve like $delete = mysql_query("truncate table name_da_table");
– Tropeço
and called $delete(); at the end of the report it worked
– Tropeço
mysql_query()
is a function removed in new versions of php andmysqli_query()
is the current function.– rray