2009
09.09

Siempre que necesitamos conectar una base de datos MySQL con PHP, debemos escribir unas cuantas instrucciones una y otra vez, para evitar esto, lo mejor es usar una clase que maneje nuestra conexión.
El siguiente, es el código de una clase que nos puede ayudar:

 PHP |  copy code |? 
001
002
<?php
003
/*
004
* database.php
005
*
006
* Copyright 2008 Vladimir Zurita <<a href="mailto:vladzur@gmail.com">vladzur@gmail.com</a>>
007
*
008
* This program is free software; you can redistribute it and/or modify
009
* it under the terms of the GNU General Public License as published by
010
* the Free Software Foundation; either version 2 of the License, or
011
* (at your option) any later version.
012
*
013
* This program is distributed in the hope that it will be useful,
014
* but WITHOUT ANY WARRANTY; without even the implied warranty of
015
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
016
* GNU General Public License for more details.
017
*
018
* You should have received a copy of the GNU General Public License
019
* along with this program; if not, write to the Free Software
020
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
021
* MA 02110-1301, USA.
022
*/
023
 
024
/********************************************************
025
* DataBase
026
* Author: Vladimir Zurita
027
*
028
* This class makes easier to insert data into a table and connect
029
* a database on MySQL
030
* *******************************************************/
031
 
032
class DataBase {
033
 
034
var $db=array('host'=>'localhost',
035
'user'=>'your_user',
036
'pass'=>'your_password',
037
'dbase'=>'your_database'
038
);
039
 
040
var $link="";
041
 
042
function connect(){
043
 
044
$this->link=mysql_connect($this->db['host'], $this->db['user'], $this->db['pass']);
045
mysql_select_db($this->db['dbase'], $this->link);
046
 
047
}
048
 
049
function close(){
050
mysql_close($this->link);
051
}
052
 
053
function query($ssql=null){
054
 
055
$this->connect();
056
if($result=mysql_query($ssql)){
057
while($row=mysql_fetch_assoc($result)){
058
$output[]=$row;
059
}
060
$this->close();
061
return $output;
062
}
063
return false;
064
}
065
 
066
function save($tabla,$data){
067
$campos=array_keys($data);
068
$desc=$this->describe_tabla($tabla);
069
foreach($campos as $campo){
070
for($i=0;$i<count($desc);$i++){
071
if($campo==$desc[$i]['Field'])$tipo=$desc[$i]['Type'];
072
}
073
if(stristr($tipo,"varchar"))$value.="'".$data[$campo]."', ";
074
if(stristr($tipo,"text"))$value.="'".$data[$campo]."', ";
075
if(stristr($tipo,"int"))$value.=$data[$campo].", ";
076
if(stristr($tipo,"blob"))$value.="'".$data[$campo]."', ";
077
$field.=$campo.", ";
078
}
079
$field=trim($field,", ");
080
$value=trim($value,", ");
081
$sql="INSERT INTO ".$tabla." (".$field.") VALUES (".$value.")";
082
//echo $sql;
083
$this->connect();
084
if($result=mysql_query($sql))return true;
085
$this->close();
086
return false;
087
}
088
 
089
function update($tabla,$data,$condicion){
090
$campos=array_keys($data);
091
$desc=$this->describe_tabla($tabla);
092
foreach($campos as $campo){
093
for($i=0;$i<count($desc);$i++){
094
if($campo==$desc[$i]['Field'])$tipo=$desc[$i]['Type'];
095
}
096
if(stristr($tipo,"varchar"))$value.=$campo."='".$data[$campo]."', ";
097
if(stristr($tipo,"text"))$value.=$campo."='".$data[$campo]."', ";
098
if(stristr($tipo,"int"))$value.=$campo."=".$data[$campo].", ";
099
if(stristr($tipo,"blob"))$value.=$campo."='".$data[$campo]."', ";
100
 
101
}
102
 
103
$value=trim($value,", ");
104
$sql="UPDATE ".$tabla." SET ".$value." WHERE ".$condicion;
105
//echo $sql;
106
$this->connect();
107
if($result=mysql_query($sql)){
108
$this->close();
109
return true;
110
}
111
$this->close();
112
return false;
113
}
114
 
115
function delete($tabla, $condicion){
116
$sql="DELETE ".$tabla." WHERE ".$condicion;
117
$this->connect();
118
if($result=mysql_query($sql)){
119
$this->close();
120
return true;
121
}
122
$this->close();
123
return false;
124
}
125
 
126
function describe_tabla($tabla){
127
$sql="DESCRIBE ".$tabla;
128
$this->connect();
129
$res=mysql_query($sql);
130
while($field=mysql_fetch_assoc($res)){
131
$output[]=array('Field'=>$field['Field'], 'Type'=>$field['Type']);
132
}
133
$this->close();
134
return $output;
135
}
136
 
137
}
138
?>
139

El modo de uso es simple, veamos un ejemplo:

 HTML |  copy code |? 
01
02
<html>
03
<head>
04
<title>sin título</title>
05
<meta http-equiv="content-type" content="text/html;charset=utf-8" />
06
<meta name="generator" content="Geany 0.14" />
07
</head>
08
<body>
09
<form method="post" action="example.php">
10
<fieldset>
11
<input type="text" name="data[name]">
12
<input type="text" name="data[last_name]">
13
<input type="text" name="data[email]">
14
<input type="text" name="data[address]">
15
<button type="submit">Save</button>
16
</fieldset>
17
</form>
18
</body>
19
</html>
20

Y recogemos el formulario con:

 PHP |  copy code |? 
01
02
<?php
03
include("database.php");
04
$DB= new DataBase();
05
if(isset($_POST['data'])){
06
$data=$_POST['data'];
07
$DB->save('user',$data);
08
exit();
09
}
10
?>
11

  • Digg
  • Facebook
  • Delicious
  • Twitter
  • Share/Bookmark
VN:F [1.9.3_1094]
Rating: 10.0/10 (2 votes cast)
PHP: Clase para conectar MySQL, 10.0 out of 10 based on 2 ratings

2 comentarios

Agregue su comantario
  1. VA:F [1.9.3_1094]
    Rating: +1 (from 1 vote)

    Que bueno que uses una clase en lugar de realizar la consulta a la diabla, quedaria mejor quitar conect() y close() dentro de save y update (solo necesitas conectar una vez y desconectar al final del script).
    Y si quiero llenar solo tres campos de una tabla con 6 campos, debo colocar
    $DB->save(‘user’,',”a”,,”b”,”c”,’);

  2. VA:F [1.9.3_1094]
    Rating: +1 (from 1 vote)

    Gracias, es bueno lo de quitar el connect() y el close(), la verdad es un poco redundante, para agregar solo unos pocos campos, solo debes indicarlos como :
    $DB->save(array('campo'=>'valor', 'campo2'=>'valor));