CRUD totalmente dinâmico
Olá.. Estou desenvolvendo um CRUD extremamente dinâmico, já é aplicável para muitas finalidades, falta ainda concluir a parte do UPDATE, pois ando meio sem tempo.
Seguem aí os códigos e assim e concluír eu atualizo.
Primeiro a conexão:
<?php
/**
*
* @author Erick Tarzia
* 07/02/2013
*
*/
class conexao
{
private $db_host = ''; // servidor
private $db_user = ''; // usuario do banco
private $db_pass = ''; // senha do usuario do banco
private $db_name = ''; // nome do banco
private $con = false;
public function connect() // estabelece conexao
{
if(!$this->con)
{
$myconn = @mysql_connect($this->db_host,$this->db_user,$this->db_pass);
if($myconn)
{
$seldb = @mysql_select_db($this->db_name,$myconn);
if($seldb)
{
$this->con = true;
return true;
}
else
{
return false;
}
}
else
{
return false;
}
}
else
{
return true;
}
}
public function disconnect() // fecha conexao
{
if($this->con)
{
if(@mysql_close())
{
$this->con = false;
return true;
}
else
{
return false;
}
}
}
}
?>
agora minha classe crud.class.php
<?php
/**
*
* @author Erick Tarzia
* 07/02/2013
*
*/
class Crud {
function pegarPrimaria($tabela) {
// $keys = Array ();
$queryChave = sprintf ( "SHOW KEYS FROM `%s`", $tabela );
$resultChave = mysql_query ( $queryChave ) or die ( "Erro: " . mysql_error () );
while ( $rowChave = mysql_fetch_assoc ( $resultChave ) ) {
if ($rowChave ['Key_name'] == 'PRIMARY') {
$chavePrimaria = $rowChave ['Column_name'];
}
}
return $chavePrimaria;
}
public function AntiInjection($param) {
$param = strip_tags ( $param ); // retirar as tags html
$param = mysql_escape_string ( $param ); // Retirar todas tags referentes
// do
// mysql ex: select, insert,
// update drop
// etc...
return $param;
}
public function retornarCamposTabela($tabela) {
$campos = array ();
$result = mysql_query ( "SHOW COLUMNS FROM " . $tabela ); // descobrir os
// campos da
// tabela
while ( $campo = mysql_fetch_assoc ( $result ) ) {
$campos [] = $campo ['Field'];
}
unset ( $campos [0] ); // retirar o primeiro campo da lista
// listar os dados do array
/*
* foreach ( $campos as $valores ) { echo $valores . "<br>"; }
*/
// retorna um array com todos os campos da tabel menos o primeiro(id)
return $campos;
}
public function inserir($table, $array) {
$insert = "INSERT INTO " . $table;
$columns = $this->retornarCamposTabela ( $table );
$data = array ();
foreach ( $array as $key => $value ) {
if ($value != "") {
$data [] = "'" . $value . "'";
} else {
$data [] = "NULL";
}
}
$cols = implode ( ",", $columns );
$values = implode ( ",", $data );
$sql = $insert . " (" . $cols . ") " . " VALUES " . " (" . $values . ") ";
$this->query ( $sql );
}
public function listar($nomeDaTabela) {
$chavePrimaria0 = $this->pegarPrimaria ( $nomeDaTabela );
$result = mysql_query ( "SHOW COLUMNS FROM " . $nomeDaTabela );
if (! $result) {
echo 'Erro: ' . mysql_error ();
exit ();
}
$totalDeCampos = mysql_num_rows ( $result ); // total de campos da tabela
$lista = mysql_query ( "select * from " . $nomeDaTabela );
// listar os dados
echo '<table align="center">';
echo ' <tr>';
$z = 0;
while ( $row = mysql_fetch_assoc ( $result ) ) {
echo ' <td>';
$nome [$z] = $row ['Field'];
$tipo [$z] = $row ['Type'];
echo "<strong>" . $nome [$z] . "</strong>";
$z ++;
echo ' </td>';
}
echo ' </tr>';
$w = 0;
while ( $linha = mysql_fetch_assoc ( $lista ) ) {
echo '<tr>';
for($w = 0; $w < $totalDeCampos; $w ++) {
echo '<td>';
echo $linha [$nome [$w]];
echo '</td>';
}
echo '</tr>';
}
echo '</table>';
}
public function apagar($tabela, $id) {
$chavePrimaria = $this->pegarPrimaria ( $tabela );
echo $chavePrimaria;
$queryApagar = "DELETE FROM " . $tabela . " where " . $chavePrimaria . " = " . $id;
$this->query ( $queryApagar );
}
public function query($sql) {
$q = mysql_query ( $sql );
if ($q) {
echo "<script>alert('Concluído');</script>";
} else {
echo "<script>alert('Erro: " . mysql_errno () . "');</script>";
}
}
}
Agora vamos a utilização:
<php
require_once 'conexao.php';
require_once 'classes/crud.class.php';
$con = new Conexao();
$con->connect();
$crud = new Crud();$crud->listar('nome_da_tabela'); // para exibir uma tabela com todos os dados.
?>
Agora vou mostrar como fazer um insert
<?php
// primeiro ver se ação é para adicionar
if(isset($_GET['acao'])){
$acao = $_GET['acao'];
if($acao == 'novo'){ // se ação for novo
$valore = array();
//pega todos os $_POST e coloca num array
foreach( $_POST as $valor => $vlr){
$valores[] = $crud->AntiInjection($vlr);
}
//mostra os valores enviados (apenas para confirmação)
foreach ( $valores as $valores0 ) {
echo $valores0 . "<br>";
}
$crud->inserir('nome_da_tabela_para_INSERT'',$valores); // chama a função que faz o insert na tabela
}
}
?>
<form method="post" action="<?php echo $_SERVER['PHP_SELF'];?>?acao=novo" >
<table align="center">
<tr>
<td>Nome</td>
<td><label for="nome"></label>
<input type="text" name="nome" id="nome" /></td>
</tr>
<tr>
<td>Nome2</td>
<td><input type="text" name="nome2" id="nome2" /></td>
</tr>
<tr>
<td>Nome3</td>
<td><input type="text" name="nome3" id="nome3" /></td>
</tr>
<tr>
<td>Nome4</td>
<td><input type="text" name="nome4" id="nome4" /></td>
</tr>
<tr>
<td>Nome5</td>
<td><input type="text" name="nome5" id="nome5" /></td>
</tr>
<tr>
<td>Nome6</td>
<td><input type="text" name="nome6" id="nome6" /></td>
</tr>
<tr>
<td> </td>
<td><input type="submit" value="Enviar" /></td>
</tr>
</table>
</form>para apagar, o princípio é o mesmo:
//recomendo criar separadamente o aquivo apagar.php, desta forma conseguirá usar em qualquer parte do sistema assim:
<a href='apagar.php?tabela=SUA_TABELA&id=ID_A _SER_APAGADO&acao=apagar'>APAGAR</a>
<?php
require_once 'conexao.php';
require_once 'classes/crud.class.php';
$con = new Conexao();
$con->connect();
$crud = new Crud();// só pra garantir que nada seja apagado acidentalmente
if(isset($_GET['acao']){
if($acao == 'apagar'){
$tabela = $_GET['tabela'];
$id = $_GET['id'];
$crud->apagar($tabela,$id);
}
}Espero que gostem e que seja útil.
assim que terminar a função de UPDATE eu atualizo!
Discussão (12)
Carregando comentários...