Skip to content

Instantly share code, notes, and snippets.

@danielbonifacio
Created July 26, 2017 19:47
Show Gist options
  • Save danielbonifacio/d96b1bb7b822dda090078b7827f22b7b to your computer and use it in GitHub Desktop.
Save danielbonifacio/d96b1bb7b822dda090078b7827f22b7b to your computer and use it in GitHub Desktop.
Conexão segura com MySQLi e PHP
<?php
date_default_timezone_set('America/Sao_Paulo');
define('DB_HOSTNAME', 'localhost');
define('DB_USERNAME', 'root');
define('DB_PASSWORD', null);
define('DB_DATABASE', 'ac_sistema');
define('DB_PREFIX', 'ac');
define('DB_CHARSET', 'UTF8');
<?php
require_once'config.php';
//Proteção contra SQLInjection
function DBEscape($dados){
$link = DBConnect();
if(!is_array($dados))
$dados = mysqli_real_escape_string($link, $dados);
else{
$arr = $dados;
foreach ($arr as $key => $value) {
$key = mysqli_real_escape_string($link, $key);
$value = mysqli_real_escape_string($link, $value);
$dados[$key] = $value;
}
}
DBClose($link);
return $dados;
}
//Fecha conexão com MySQL
function DBClose($link){
@mysqli_close($link) or die(mysqli_error($link));
}
//Abre conexão com MySQL
function DBConnect(){
$link = @mysqli_connect(DB_HOSTNAME, DB_USERNAME, DB_PASSWORD, DB_DATABASE) or die(mysqli_connect_error());
mysqli_set_charset($link, DB_CHARSET) or die(mysqli_error($link));
return $link;
}
<?php
require_once'connection.php';
//Deleta registros
function DBDelete($table, $where = null){
$table = DB_PREFIX.'_'.$table;
$where = ($where) ? " WHERE {$where}" : null;
$query = "DELETE FROM {$table}{$where}";
DBExecute($query);
}
//Altera registros
function DBUpdate($table, array $data, $where = null){
foreach ($data as $key => $value) {
$fields[] = "{$key} = '{$value}'";
}
$fields = implode(', ', $fields);
$table = DB_PREFIX.'_'.$table;
$where = ($where) ? " WHERE {$where}" : null;
$query = "UPDATE {$table} SET {$fields}{$where}";
return DBExecute($query);
}
//Lê registros no banco de dados
function DBRead($table, $params = null, $fields = '*'){
$table = DB_PREFIX.'_'.$table;
$params = $params ? " {$params}" : null;
$query = "SELECT {$fields} FROM {$table}{$params}";
$result = DBExecute($query);
if(!mysqli_num_rows($result))
return false;
else{
while ($res = mysqli_fetch_assoc($result)) {
$data[] = $res;
}
return $data;
}
}
//Insere no banco de dados
function DBCreate($table, array $data){
$table = DB_PREFIX.'_'.$table;
$data = DBEscape($data);
$fields = implode(', ', array_keys($data));
$values = "'".implode("', '", $data)."'";
$query = "INSERT INTO {$table} ( {$fields} ) VALUES ( {$values} )";
return DBExecute($query);
}
//Executa Queries
function DBExecute($query){
$link = DBConnect();
$result = @mysqli_query($link, $query) or die(mysqli_error($link));
DBClose($link);
return $result;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment