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', '', 'videoaulasbrasil');
- $bd->connect();
- //PARA INSERIR
- $data = array('categoria' => 'Informática', 'texto' => 'Tagtagatag');
- $bd->insert('categorias', $data);
- //PARA ALTERAR
- $data = array('categoria' => 'Informática 2 ', 'texto' => 'Tagtagatag 2');
- $bd->update('categorias', $data, "id = 5");
- //PARA EXCLUIR
- $bd->delete('categorias', "id = 5");
- ///Lista todo os itens
- $strSQL = "SELECT * FROM categorias";
- foreach ($bd->fetchAll($strSQL) as $k => $v){
- echo $v['categoria'];
- }
- //Retornar apenas uma linha
- $strSQL = "SELECT * FROM categorias WHERE id = 4";
- $row = $bd->fetchOne($strSQL);
- echo $row['categoria'];
- //Total de Registro
- $strSQL = "SELECT * FROM categorias";
- echo $bd->numRows($strSQL);
- ?>
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement