Ir para conteúdo

Arquivado

Este tópico foi arquivado e está fechado para novas respostas.

João Paulo Hildebrand

Alterar imagem Banco de Dados

Recommended Posts

Galera, to quebrando a cabeça faz horas e horas, já procurei na net e nada de me encontrar. Sou leigo em programação ...

Consigo inserir e deletar dados no banco, porém alterar a imagem não sei como!!!!

Quero fazer a alteração de uma imagem que está no banco de dados através de um form. Estou conseguindo alterar tudo, o título da notícia, resumo, autor, data e texto, o único campo que não consigo é o da imagem. Podem me ajudar?

 

Estou usando as ferramentas do Dreamweaver cs6, mas se precisar mexer no código manualmente tamo aê :D

 

Minha tabela no banco de dados se chama noticias, com os campos: id, titulo, resumo, autor, data, categoria, imagem, noticia

 

Segue abaixo meu código Alterar

 

 

alterar.php

 

<?php require_once('../Connections/conexao_banco_agenciaconectal.php'); ?>
<?php
if (!function_exists("GetSQLValueString")) {
function GetSQLValueString($theValue, $theType, $theDefinedValue = "", $theNotDefinedValue = "")
{
if (PHP_VERSION < 6) {
$theValue = get_magic_quotes_gpc() ? stripslashes($theValue) : $theValue;
}
$theValue = function_exists("mysql_real_escape_string") ? mysql_real_escape_string($theValue) : mysql_escape_string($theValue);
switch ($theType) {
case "text":
$theValue = ($theValue != "") ? "'" . $theValue . "'" : "NULL";
break;
case "long":
case "int":
$theValue = ($theValue != "") ? intval($theValue) : "NULL";
break;
case "double":
$theValue = ($theValue != "") ? doubleval($theValue) : "NULL";
break;
case "date":
$theValue = ($theValue != "") ? "'" . $theValue . "'" : "NULL";
break;
case "defined":
$theValue = ($theValue != "") ? $theDefinedValue : $theNotDefinedValue;
break;
}
return $theValue;
}
}
$editFormAction = $_SERVER['PHP_SELF'];
if (isset($_SERVER['QUERY_STRING'])) {
$editFormAction .= "?" . htmlentities($_SERVER['QUERY_STRING']);
}
if ((isset($_POST["MM_update"])) && ($_POST["MM_update"] == "form1")) {
$updateSQL = sprintf("UPDATE noticias SET titulo=%s, resumo=%s, autor=%s, `data`=%s, categoria=%s, imagem=%s, noticia=%s WHERE id=%s",
GetSQLValueString($_POST['titulo'], "text"),
GetSQLValueString($_POST['resumo'], "text"),
GetSQLValueString($_POST['autor'], "text"),
GetSQLValueString($_POST['data'], "text"),
GetSQLValueString($_POST['categoria'], "text"),
GetSQLValueString($_FILES['imagem'], "text"),
GetSQLValueString($_POST['noticia'], "text"),
GetSQLValueString($_POST['id'], "int"));
mysql_select_db($database_conexao_banco_agenciaconectal, $conexao_banco_agenciaconectal);
$Result1 = mysql_query($updateSQL, $conexao_banco_agenciaconectal) or die(mysql_error());
$updateGoTo = "gerenciar.php";
if (isset($_SERVER['QUERY_STRING'])) {
$updateGoTo .= (strpos($updateGoTo, '?')) ? "&" : "?";
$updateGoTo .= $_SERVER['QUERY_STRING'];
}
header(sprintf("Location: %s", $updateGoTo));
}
$colname_alterar = "-1";
if (isset($_GET['id'])) {
$colname_alterar = $_GET['id'];
}
mysql_select_db($database_conexao_banco_agenciaconectal, $conexao_banco_agenciaconectal);
$query_alterar = sprintf("SELECT * FROM noticias WHERE id = %s", GetSQLValueString($colname_alterar, "int"));
$alterar = mysql_query($query_alterar, $conexao_banco_agenciaconectal) or die(mysql_error());
$row_alterar = mysql_fetch_assoc($alterar);
$totalRows_alterar = mysql_num_rows($alterar);
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Editar Postagem</title>
<link rel="stylesheet" href="css/style_admin.css" />
</head>
<body>
<div id="alinhamento_cadastro">
<h1>Editar Postagem</h1>
<form action="<?php echo $editFormAction; ?>" method="post" name="form1" id="form1">
<table align="center">
<tr valign="baseline">
<td nowrap="nowrap" align="right">Titulo:</td>
<td><input type="text" name="titulo" value="<?php echo htmlentities($row_alterar['titulo'], ENT_COMPAT, 'utf-8'); ?>" size="32" /></td>
</tr>
<tr valign="baseline">
<td nowrap="nowrap" align="right">Resumo:</td>
<td><input type="text" name="resumo" value="<?php echo htmlentities($row_alterar['resumo'], ENT_COMPAT, 'utf-8'); ?>" size="32" /></td>
</tr>
<tr valign="baseline">
<td nowrap="nowrap" align="right">Autor:</td>
<td><input type="text" name="autor" value="<?php echo htmlentities($row_alterar['autor'], ENT_COMPAT, 'utf-8'); ?>" size="32" /></td>
</tr>
<tr valign="baseline">
<td nowrap="nowrap" align="right">Data:</td>
<td><input type="date" name="data" value="<?php echo htmlentities($row_alterar['data'], ENT_COMPAT, 'utf-8'); ?>" size="32" /></td>
</tr>
<tr valign="baseline">
<td nowrap="nowrap" align="right">Categoria:</td>
<td><input type="text" name="categoria" value="<?php echo htmlentities($row_alterar['categoria'], ENT_COMPAT, 'utf-8'); ?>" size="32" /></td>
</tr>
<tr valign="baseline">
<td nowrap="nowrap" align="right">Imagem:</td>
<td><input type="file" name="imagem" value="<?php echo htmlentities($row_alterar['imagem'], ENT_COMPAT, 'utf-8'); ?>" size="32" /></td>
</tr>
<tr valign="baseline">
<td nowrap="nowrap" align="right">Noticia:</td>
<td><input type="text" name="noticia" value="<?php echo htmlentities($row_alterar['noticia'], ENT_COMPAT, 'utf-8'); ?>" size="32" /></td>
</tr>
<tr valign="baseline">
<td nowrap="nowrap" align="right"> </td>
<td><input type="submit" value="Update record" /></td>
</tr>
</table>
<input type="hidden" name="MM_update" value="form1" />
<input type="hidden" name="id" value="<?php echo $row_alterar['id']; ?>" />
</form>
<p> </p>
</div><!--alinhamento-->
</body>
</html>
<?php
mysql_free_result($alterar);
?>

 

Compartilhar este post


Link para o post
Compartilhar em outros sites

Posso ser meio doido por não ter lido seu código por estar um pouco grande e embolado mas tentando te ajudar pela duvida somente temos que verificar um ponto, no campo imagem você está pegando apenas o nome da imagem? se tiver você vai fazer o que, na pagina de atualizar você fara o seguinte:

 

1 comparar os nomes das imagens no campo do banco de dados

2 verificar se a imagem cadastrada atualmente ainda existe na pasta

3 apagar a imagem da pasta se existir isso pra nao ocupar espaço no banco de dados

4 dar o update fazendo seu novo upload de imagem e pronto.

 

Pude notar que voce usa o DW cs6 não sei se esta usando ferarmentas dele, mas te do uma dica desde já para de usar a engine pra gerar codigos pra você eu também usava ta e parei devido a grande quantidade de duvidas e por nao conseguir resolve-las php e facil e voce pega com um mes o basico dele, digo basico pra criar mini sistemas como tal. Abraços amigo qualquer coisa estamos ai .

Compartilhar este post


Link para o post
Compartilhar em outros sites

Olá srnalim!

Realmente, está muito confuso este código. Por esse motivo, resolvi botar a mão na massa e fazê-lo manualmente, agora está muito mais simples e fácil de se ler.

Seguinte: Estou conseguindo alterar todos os campos normalmente, o único que não altera é a imagem. Não sei se foi isso que você quis dizer, mas quero fazer com que a função UPDATE atualize a referencia da imagem.

Como disse, sou leigo em programação.

Quero que o UPDATE atualize a referencia do banco de dados, apagando e inserindo este novo registro automaticamente.

 

Muitíssimo obrigado pela ajuda! Mas estou fazendo esta nova descrição pois não entendi muito bem o que você me escreveu ...

 

Segue meu novo codigo:

alterar.php

 

 

 

<?php
include("../Connections/conexao_banco_agenciaconectal.php");
?>
<?php
$id = $_GET["id"];
$sql = mysql_query("select * from noticias where id='$id'");
$exibe = mysql_fetch_assoc($sql);
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Cadastrar Notícia</title>
<link rel="stylesheet" href="css/style_admin.css" />
</head>
<body>
<div id="alinhamento_cadastro">
<h1>Cadastro de Postagem</h1>
<form action="metodo_alterar.php" method="post" enctype="multipart/form-data" name="cadastro" >
<input name="id" type="hidden" value="<?php echo $exibe["id"] ?>" />
<input type="text" name="titulo" class="titulo" placeholder="Título da Postagem" required="required" value="<?php echo $exibe["titulo"] ?>"/><br />
<input type="text" name="resumo" class="resumo" placeholder="Resumo da Postagem" required="required" value="<?php echo $exibe["resumo"] ?>"/><br />
<input type="text" name="autor" class="autor" placeholder="Autor da Postagem" required="required" value="<?php echo $exibe["autor"] ?>"/><br />
<input type="date" name="data" class="data" placeholder="Data da Postagem" required="required" value="<?php echo $exibe["data"] ?>"/><br />
<span class="titulo_categoria">Categoria:</span>
<input type="radio" name="categoria" value="noticias_em_geral" class="radio_btn" />Notícias em Geral <br />
<input type="radio" name="categoria" value="tecnologia" class="radio_btn2" />Tecnologia
<input name="foto" type="hidden" />
<input type="file" name="foto" class="foto" value="<?php echo $exibe["foto"] ?>"/><br />
<textarea name="texto" class="texto" placeholder="Texto da Postagem" required="required"><?php echo $exibe["noticia"] ?></textarea><br />
<button value="Cadastrar" name="cadastrar" class="cadastrar" id="upload">Cadastrar Notícia</button>
<button value="Resetar" name="resetar" class="resetar">Resetar Notícia</button>
</form>
</div><!--alinhamento-->
</body>
</html>

 

metodo_alterar.php

 

 

 

<?php
include("../Connections/conexao_banco_agenciaconectal.php");
?>
<?php
$id = $_POST["id"];
$titulo = $_POST["titulo"];
$resumo = $_POST["resumo"];
$autor = $_POST["autor"];
$data = $_POST["data"];
$categoria = $_POST["categoria"];
$foto = $_FILES["foto"];
$noticia = $_POST["texto"];
if(mysql_query("update noticias set titulo='$titulo', resumo='$resumo', autor='$autor', data='$data', categoria='$categoria', imagem='$foto', noticia='$noticia' where id='$id'")){
echo "Postagem Alterada com Sucesso! <br> <a href='gerenciar.php'>Voltar</a>";
exit;
}else{
echo mysql_error();
exit;
}
?>

Compartilhar este post


Link para o post
Compartilhar em outros sites

("UPDATE notocias SET (titulo,resumo,autor,data,categoria,imagem,noticia)
                VALUES ('".addslashes($titulo)."',
                '".addslashes($resumo)."',
                '".addslashes($autor)."',
                '".addslashes($data)."',
                '".addslashes($categoria)."',
                '".addslashes($imagem)."',
                '".addslashes($noticia)."')
                WHERE id = '$id' ")

 

sou novo em php + tente isso

Compartilhar este post


Link para o post
Compartilhar em outros sites

×

Informação importante

Ao usar o fórum, você concorda com nossos Termos e condições.