Usamos cookies para medir audiência e melhorar sua experiência. Você pode aceitar ou recusar a qualquer momento. Veja sobre o iMasters.
Pessoal estou postando meu código novamente... pois estou perdendo muito tempo com esta dúvida, creio eu que seja simples de resolver... Imagina que possa ser com relação a objetos, talvez...
Aguardo,,,
O que acontece aki... na meu projeto tem um php chamado CadastroAgenda.php , senda esta minha visão, na qual possui um switch que chama alguns métodos, Caso: variável $acaoAg, receba "novo" ela chama um insert com valor nulo e me retorna o valor do último registro "id", dai armazeno o valor em uma variável "$id" a qual é enviada por POST, quando o form chama o AgendaControl.php, ele também faz uma comparação com Switch recebendo como valor "alterar", que este passa todo o conteúdo de um Array com os valores do form, para os "Sets" da minha classe Agenda.class.php(bean), logo em seguida, após os "Sets", instancio um novo objeto tipo AgendaDAO(), dai chamo o método alteraEvento(), e passo como parametro o objeto $agenda, com a intenção de realizar um update na tabela na linha com aquele id gerado logo no inicio da minha visão, gerado pelo método insereEvento(), do meu AgendaControl.
O meu maior problema:executa todas os métodos (funções), porém não consigo atualizar de fato a minha tabela, além do que não me retorna nenhum tipo de exceção,pior ainda,quendo dou um echo $agenda->getEvento() ou $agenda->getId() dentro do bloco da função alteraEvento() atualiza consigo imprimir os valores, porém com o sql aparentemente nada acontece, nada mesmo nenhum errinho para descontrair..
Irei postar tudo que tenho...
config/config.php
<?php
define ("DB_DRIVER",'mysql');
define("DB_HOST","localhost");
define("DB_NAME","baladajov");
define("DB_USER","root");
define("DB_PASS","");
if(is_file("config/ChromePhp.php")){
require_once("config/ChromePhp.php");
}else
if(is_file("../config/ChromePhp.php")){
require_once("../config/ChromePhp.php");
}else
if(is_file("../../config/ChromePhp.php")){
require_once("../../config/ChromePhp.php");
}else{echo"Arquivo de Debug não encontrado.";}
function __autoload($className){
if(is_file("classes/model/".$className.".class.php")){
require_once("classes/model/".$className.".class.php");
}else
if(is_file("../model/".$className.".class.php")){
require_once("../model/".$className.".class.php");
}else
if(is_file("classes/bd/".$className.".class.php")){
require_once("classes/bd/".$className.".class.php");
}else
if(is_file("../bd/".$className.".class.php")){
require_once("../bd/".$className.".class.php");
}else
if(is_file("classes/control/".$className.".class.php")){
require_once("classes/control/".$className.".class.php");
}else
if(is_file("../control/".$className.".class.php")){
require_once("../control/".$className.".class.php");
}else{
echo"Classe '".$className."' não existe:<br/>";
}
}
?>
classes/bd/Conexao.class.php
<?php
if(is_file("config/config.php")){
require_once("config/config.php");
}else
if(is_file("../config/config.php")){
require_once("../config/config.php");
}else
if(is_file("../../config/config.php")){
require_once("../../config/config.php");
}else{echo"Arquivo config não encontrado.";}
class Conexao extends PDO {
public $handle = null;
function __construct() {
try {
if ( $this->handle == null ) {
$dbh = parent::__construct(DB_DRIVER.":host=".DB_HOST.";dbname=".DB_NAME, DB_USER, DB_PASS);
$this->handle = $dbh;
return $this->handle;
}
}
catch ( PDOException $e ) {
echo 'Connection failed: ' . $e->getMessage( );
return false;
}
}
//aqui criamos um objeto de fechamento da conexão
function __destruct( ) {
$this->handle = NULL;
}
/* private static $instancia;
public function Conexao() {
// O construtro abaixo é o do PDO
parent::__construct(DB_DRIVER.":host=".DB_HOST.";dbname=".DB_NAME, DB_USER, DB_PASS);
}
public static function getInstance() {
// Se o a instancia não existe eu faço uma
if(!isset( self::$instancia )){
try {
self::$instancia = new PDO(DB_DRIVER.":host=".DB_HOST.";dbname=".DB_NAME, DB_USER, DB_PASS);
//DB_DRIVER.":host=".DB_HOST.";dbname=".DB, DB_USER, DB_PASS
} catch (PDOException $e ) {
echo ("Erro ao conectar. Erro:".$e->getMessage());
exit ();
}
}
// Se já existe instancia na memória eu retorno ela
return self::$instancia;
}
*/
}
?>
classes/view/CadastraEvento.php
<?php
require_once("classes/control/AgendaControl.php");
if(isset($_GET['acaoAg'])){
$acao =$_GET['acaoAg'];
switch($acao){
case "novo":
$id = insereEvento();
echo"Id recebido do DAO:".$id;
$acaoControl = 'alterar';
break;
case "alter":
echo "alterar Evento";
/*
$agendaControl = new AgendaControl();
$agendaControl->atualizaEvento();
*/
break;
}
}
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<style type="text/css">
#divAlerta {
background-color:#09F;
font-family:Verdana, Geneva, sans-serif;
font-size:12px;
font-weight:bold;
width: 300px;
height: ;
}
.loader {
display: none;
float: left;
}
</style>
<title>Documento sem título</title>
<link type="text/css" href="scripts/jquey_ui/css/custom-theme/jquery-ui-1.8.23.custom.css" rel="stylesheet" />
<link type="text/css" href="style/forms_admin.css" rel="stylesheet" />
<script type="text/javascript" src="scripts/jquey_ui/js/jquery-ui-1.8.23.custom.min.js"></script>
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.4.4/jquery.min.js"></script>
</head>
<body>
<div id="wrapper">
<h1>Give us your feedback</h1>
<div id="inner-wrapper">
<form id="feedback" action="classes/control/AgendaControl.php" method="post">
<div id="response"><!--This will hold our error messages and the response from the server. --></div>
<input name="acao" type="hidden" id="acao" value="<?php echo $acaoControl; ?>" />
<input name="id" type="hidden" class="required" id="id" value="
<?php if($id!=null){echo $id;}?>" />
<div class="inputs">
<label>Evento</label>
<input name="evento" type="text" class="required" id="evento" size="30" />
</div>
<div class="inputs">
<label>Local</label>
<input name="local" type="text" class="required" id="local" size="30" />
</div>
<div class="inputs">
<label>Data</label>
<input name="data1" type="text" class="required" id="data1" size="30" />
</div>
<div class="inputs">
<label>Data Encerramento</label>
<input name="data2" type="text" class="required" id="data2" size="30" />
</div>
<div class="inputs">
<label>Descrição Breve</label>
<textarea name="descBreve" cols="25" rows="" class="required" id="descBreve"></textarea>
</div>
<div class="inputs">
<label>Descrição Completa</label>
<textarea name="descricao" cols="25" rows="" class="required" id="descricao"></textarea>
</div>
<div class="button">
<input type="submit" name="submit" id="submit" value="Submit" />
</div>
</form>
</div><!-- End inner-wrapper -->
</div><!-- End wrapper -->
</body>
</html>
classes/control/AgendaControl.php
<?php
if(is_file("config/config.php")){
require_once("config/config.php");
}else
if(is_file("../config/config.php")){
require_once("../config/config.php");
}else
if(is_file("../../config/config.php")){
require_once("../../config/config.php");
}else{echo"Arquivo confignão encontrad.";}
if(isset($_REQUEST["acao"])){
$acao = $_REQUEST["acao"];
$v = $_REQUEST;
/*$dadosEvento = array($v['id'],$v['evento'],$v['data1'],$v['data2'],$v['descBreve'],$v['descricao'],$v['local']);*/
switch($acao){
case 'iniciaCad':{
}
case 'concluiCad':{
}
case 'excluir':{
}
case 'alterar':{
$agenda = new Agenda();
$id=$v['id'];
echo "<br/>Valor sendo passado recebido pelo form:".$id;
$agenda->setEvento($v['evento']);
$agenda->setData1($v['data1']);
$agenda->setData2($v['data2']);
$agenda->setDescBreve($v['descBreve']);
$agenda->setDescricao($v['descricao']);
$agenda->setLocal($v['local']);
$agendaDAO = new AgendaDAO();
$agendaDAO->alteraEvento($agenda,$id);
}
default:
return null; //Por padrão, esse switch não retorna nada.
}echo"<br/>Não existe REQUEST!<br/>";
}
function insereEvento(){
$agendaDAO = new AgendaDAO();
return $agendaDAO->insereEvento();
}
?>
classes/model/AgendaDAO.class.php
<?php
class AgendaDAO{
private $agendaDAO;
private $oConexao;
public function __construct(){
$this->oConexao = new Conexao();
}
public function insereEvento(){
try{
//$this->oConexao->beginTransaction();
$stmt = $this->oConexao->prepare("INSERT INTO AGENDA (id) VALUES (null)");
$stmt->execute();
//$this->oConexao->commit();
$id = $this->oConexao->lastInsertId();
return ($id);
$this->oConexao=null;
}catch(PDOException $e){
$this->oConexao->rollBack();//Se houver alguma exceção, retrocede as alterações feitas no banco.
echo $e->getCode();
}
}
/*public function insereEvento(){
try{
$agenda = new Agenda();
$agendaDAO = new AgendaDAO();
$this->oConexao->beginTransaction();
$stmt = $this->oConexao->prepare("INSERT INTO AGENDA (id) VALUES (null)");
$stmt->execute();
$this->oConexao->commit();
echo"Transação realizada<br/>";
//echo $agendaDAO->retornaUltimoIdEvento();
$agenda->setId($agendaDAO->retornaUltimoIdEvento());
return ($agenda);
}catch(PDOException $e){
$this->oConexao->rollBack();//Se houver alguma exceção, retrocede as alterações feitas no banco.
echo $e->getMessage();
}
}*/
public function alteraEvento($agenda,$condicao){
$evento = "Fim do mundo 2";
$cond = $condicao;
try{
echo "Condição: ".$condicao;
$sql = "UPDATE agenda SET evento=? WHERE id=?";
$stmt = $this->oConexao->prepare($sql);
$stmt->execute(array($evento,$cond));
}catch ( PDOException $ex ){ echo "Erro: ".$ex->getCode(); }
}
/*try{
$oConexao = Conexao::getInstance();//Realiza conexao
//Tratamento de datas
$data1 = $this->datasql($agenda->getData1());
$data2 = $this->datasql($agenda->getData2());
//Prepara a instrução
$stmt = $oConexao->prepare("UPDATE AGENDA SET evento=?, data1=?, data2=?, desc_breve=?, descricao=?, local=? WHERE id=?");
$oConexao->beginTransaction(); //Abre a transação com o bd e ainda desliga o auto commit;
$stmt->bindValue(1,$agenda->getEvento());
$stmt->bindValue(2,$data1);
$stmt->bindValue(3,$data2);
$stmt->bindValue(4,$agenda->getDescBreve());
$stmt->bindValue(5,$agenda->getDescricao());
$stmt->bindValue(6,$agenda->getLocal());
$stmt->bindValue(7,$condicao);//simples comparação para saber se deu certo ou não a execução do sq
$msg = $stmt === TRUE ? 'Atualizado com sucesso!' : 'Falha ao tentar atualizar'; echo $msg;
$oConexao->commit(); //finaliza a transação
}catch(Exception $e){
//$oConexao->rollBack();//Se houver alguma exceção, retrocede as alterações feitas no banco.
echo $e->getMessage();
}public function consultaEventoPorId($agenda){
try{
$this->oConexao = Conexao::getInstance();
$oConexao->beginTransaction();
$stmt = $this->oConexao->prepare("SELECT *FROM agenda WHERE id='?')");
$stmt->bindValue(1,$agenda->getId());
$stmt->execute();
$this->oConexao->commit();
$evento = $stmt->fetchall(PDO::FETCH_ASSOC);
}catch(PDOException $e){
$this->oConexao->rollBack();//Se houver alguma exceção, retrocede as alterações feitas no banco.
echo $e->getMessage();
}
}
// Formata data aaaa-mm-dd para dd/mm/aaaa
function databr($datasql) {
if (!empty($datasql)){
$p_dt = explode('-',$datasql);
$data_br = $p_dt[2].'/'.$p_dt[1].'/'.$p_dt[0];
return $data_br;
}
}
// Formata data dd/mm/aaaa para aaaa-mm-dd
function datasql($databr) {
if (!empty($databr)){
$p_dt = explode('/',$databr);
$data_sql = $p_dt[2].'-'.$p_dt[1].'-'.$p_dt[0];
return $data_sql;
}
}
public function removeEvento(){
}
}
?>
classe/model/Agenda.class.php
<?php
class Agenda{
private $id;
private $evento;
private $data1;
private $data2;
private $descBreve;
private $descricao;
private $local;
//Getters e Setters
public function setId($id){
$this->id = $id;
}
public function getId(){
return $this->id;
}
public function setEvento($evento){
$this->evento = $evento;
}
public function Teste(){
return $this->teste;
}
public function getEvento(){
return $this->evento;
}
public function setData1($data1){
$this->data1 = $data1;
}
public function getData1(){
return $this->data1;
}
public function setData2($data2){
$this->data2 = $data2;
}
public function getData2(){
return $this->data2;
}
public function setDescBreve($descBreve){
$this->descBreve = $descBreve;
}
public function getDescBreve(){
return $this->descBreve;
}
public function setDescricao($descricao){
$this->descricao = $descricao;
}
public function getDescricao(){
return $this->descricao;
}
public function setLocal($local){
$this->local = $local;
}
public function getLocal(){
return $this->local;
}}
?>
Index.php
<?php
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Documento sem título</title>
</head>
<?php
include("classes/view/cadastroEvento.php");
?>
<body>
</body>
</html>
Já não sei o que fazer... Já perdi várias noites de sono e nada...
Help Me!!!
Carregando comentários...