Para eso usas algo que se conoce como "ActiveRecord", usas una clase base ej:
Código PHP:
class DBTable {
protected $table;
protected $keyColumn = 'id';
private $properties = array();
private $db;
public function __construct() {
$table = get_class($this);
$this->db = new Conexion();
}
public function __get( $name ) {
if( isset( $this->properties[$name] ) ) {
return $this->properties[$name];
} else {
return null;
}
}
public function __set( $name, $value ) {
$this->properties[$name] = $value;
}
public function clean() {
$this->properties = array();
}
public function Agregar() {
$q = 'INSERT INTO %s ( %s ) VALUES ( %s )';
$columns = implode( ",", array_keys( $this->properties ) );
$values = array_values( $this->properties );
foreach( $values as &$value ) {
$value = "'" . addslashes( $value ) . "'";
}
$values = implode( ",", $values );
$this->db->Query( sprintf( $q, $this->table, $columns, $values );
return true;
}
public function Buscar( $campo, $valor ) {
$q = 'SELECT * FROM `%s`=\'%s\'';
$result = $db->Query( sprintf( $q, $this->tabla, $campo, $valor );
return $result->fetchRow();
}
public function Update($id) {
$q = 'UPDATE %s SET %s WHERE `%s`=\'%s\' LIMIT 1';
$update = array();
foreach( $this->properties as $key => $value ) {
$update[] = "`$key`='" . addslashes( $value ) . "'";
}
$this->db->Query( sprintf( $q, $this->table, implode( ",", $update ), $this->keyColumn, $id );
return true;
}
}
y solo "heredas" a la clase que nescesitas ej:
Código PHP:
class Alumnos extends DBTable {}
$alumnos = new Alumnos();
$alumnos->nombre = "Fulanito";
$alumnos->apellido = "Perez";
$alumnos->edad = "35";
// Insertamos valores
$alumnos->Agregar();
// Borramos valores existentes
$alumnos->clean();
// Buscamos por un campo
$resultado = $alumnos->Busca( "nombre", "Fulanito" );
Y asi el codigo es muchisimo mas dinamico.