Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- <?php
- class MySQL{
- private $host;
- private $user;
- private $pass;
- private $dbName;
- public function __construct($host, $user, $pass, $dbName){
- $this->host = $host;
- $this->user = $user;
- $this->pass = $pass;
- $this->dbName = $dbName;
- }
- public function connect(){
- if(!mysql_connect($this->host, $this->user, $this->pass)){
- die('Erro de Conexão :'.mysql_error());
- }else{
- if(!mysql_select_db($this->dbName)){
- die('Erro de DB :'.mysql_error());
- }
- }
- }
- function insert($table, array $data){
- $value = array();
- foreach($data as $v){
- $value[] = "'".$this->escape($v)."'";
- }
- $strSQL = "INSERT INTO %s (%s) VALUES (%s) ";
- $strSQL = sprintf($strSQL, $table, implode(',',array_keys($data)), implode(',', $value));
- return $this->query($strSQL);
- }
- function update($table, array $data, $where){
- $strSQL = "UPDATE %s SET %s WHERE %s ";
- $value = array();
- foreach ($data as $k => $v){
- $value[] = sprintf("%s = '%s'", $k, $this->escape($v));
- }
- $strSQL = sprintf($strSQL, $table, implode(',', $value, $where));
- return $this->query($strSQL);
- }
- function delete($table, $where){
- $strSQL = "DELETE FROM %s WHERE %s";
- $strSQL = sprintf($strSQL, $table, $where);
- return $this->query($strSQL);
- }
- function numRows($strSQL){
- $query = $this->query($strSQL);
- return mysql_num_rows($query);
- }
- function fetchAll($strSQL){
- $result = array();
- $query = $this->query($strSQL);
- while($row = mysql_fetch_assoc($query)){
- $result[] = $row;
- }
- return $result;
- }
- function fetchOne($strSQL){
- $query = $this->query($strSQL);
- return mysql_fetch_assoc($query);
- }
- function query($strSQL){
- if(!$conn = mysql_query($strSQL)){
- die('Error '.mysql_error());
- }
- return $conn;
- }
- function escape($str){
- return mysql_real_escape_string($str);
- }
- function lastId(){
- return mysql_insert_id();
- }
- }
- $bd = new MySQL('localhost', 'root', '', 'banco_de_dados');
- $bd->connect();
- //PARA INSERIR
- $data = array('campo1' => 'valor1', 'campo2' => 'valor2');
- $bd->insert('nome_da_tabela', $data);
- //PARA ALTERAR
- $data = array('campo1' => 'valor11', 'campo2' => 'valor22');
- $bd->update('nome_de_tabela', $data, "idTabela = 1");
- //PARA EXCLUIR
- $bd->delete('nome_de_tabela', "idTabela = 1");
- ///Lista todo os itens
- $strSQL = "SELECT * FROM tabela";
- foreach ($this->fetchAll($strSQL) as $k => $v){
- echo $v['nome_do_campo'];
- }
- //Retornar apenas uma linha
- $strSQL = "SELECT * FROM tabela WHERE idTabela = 1";
- $row = $bd->fetchOne($strSQL);
- //Total de Registro
- $strSQL = "SELECT * FROM tabela";
- echo $db->numRows($strSQL);
- ?>
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement