Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- <?php
- class MySQL{
- private static $conn;
- private $host;
- private $user;
- private $pass;
- private $bd;
- public function __construct($host, $user, $pass, $bd){
- $this->host = $host;
- $this->user = $user;
- $this->pass = $pass;
- $this->bd = $bd;
- $this->connect();
- }
- //Conexão com banco de dados
- public function connect(){
- if(!$conn = mysql_connect($this->host, $this->user, $this->pass)){
- die('Erro ao conectar :'.mysql_error());
- }else{
- if(!mysql_select_db($this->db, $conn)){
- die('Erro ao selecionar :'.mysql_error());
- }
- }
- }
- //executa o SQL
- public function query($sql){
- if(!$query = mysql_query($sql)){
- die('Erro executar query :'.mysql_error());
- }else{
- return $query;
- }
- }
- //inseri dados
- public function insert($table, array $data){
- $strSQL = "INSERT INTO %s (%s) VALUES(%s)";
- $value = array();
- foreach($data as $k => $v){
- $value[] = sprintf("'%s'", $this->escape($v));
- }
- $strSQL = sprintf($strSQL, $table, implode(', ', array_keys($data)), implode(', ', $value));
- $this->query($strSQL);
- }
- //altera dados
- public function update($table, array $data, array $where){
- $strSQL = "UPDATE %s SET %s WHERE %s";
- $field = array();
- $fieldW = array();
- foreach($data as $k => $v){
- $field[] = sprintf("%s='%s'", $k, $this->escape($v));
- }
- foreach($where as $k => $v){
- $fieldW[] = sprintf("%s='%s'", $k, $this->escape($v));
- }
- $strSQL = sprintf($strSQL, $table, implode(', ', $field), implode(' AND', $fieldW));
- $this->query($strSQL);
- }
- //excluir dados
- public function delete($table, array $where){
- $strSQL = "DELETE FROM %s WHERE %s";
- $field = array();
- foreach($where as $k => $v){
- $field[] = sprintf("%s='%s'", $k, $this->escape($v));
- }
- $strSQL = sprintf($strSQL, $table, implode(' AND ', $field));
- $this->query($strSQL);
- }
- //resume a execução dos comandos INSERT, UPDATE, DELETE
- public function execute($type, $table, $data=null, $where = null){
- swicth($type){
- case 'insert':
- $this->insert($table, $data);
- break;
- case 'update':
- $this->update($table, $data, $where);
- break;
- case 'delete':
- $this->update($table, $where);
- break;
- }
- }
- //escapa a string
- public function escape($value){
- return mysql_real_escape_string(stripslashes($value));
- }
- }
- //********************************UTILIZANDO******************************************//
- $mysql = new MySQL('localhost', 'root', '', 'banco_de_dados');
- //INSERIR DADOS
- $data = array('nome' => 'David', 'estado' =>'rj');
- $mysql->execute('insert', 'contato', $data);
- //ALTERAR DADOS
- $data = array('nome' => 'David CHC', 'estado' =>'RJ');
- $where = array("id" => 15);
- $mysql->execute('update', 'contato', $data, $where);
- //EXCLUIR DADOS
- $where = array("id" => 4);
- $mysql->execute('delete', 'contato', null, $where);
- ?>
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement