Jump to content

[Resolvido] Update consoante campo da imagem


Recommended Posts

Posted

Bom di,

eu tenho este codigo onde faço o upload de uma imagem e o update:

<?PHP
$select_img="SELECT * FROM news WHERE id='".$_GET['id']."'";
$query_img=mysql_query($select_img) or die(mysql_error());
$img=mysql_fetch_assoc($query_img);

error_reporting(0);
$change="";
$abc="";
define ("MAX_SIZE","400");
function getExtension($str) {
$i = strrpos($str,".");
if (!$i) { return ""; }
$l = strlen($str) - $i;
$ext = substr($str,$i+1,$l);
return $ext;
}
$errors=0;
if($_SERVER["REQUEST_METHOD"] == "POST"){
$image =$_FILES["file"]['name'];
$uploadedfile = $_FILES['file']['tmp_name'];
$title = $_POST['title'];
$type = $_POST['type'];
$text = $_POST['texto'];
$category = $_POST['category'];

if($img['img_news']==''){
 if (empty($image) || empty($uploadedfile) || empty($category) || empty($title) || empty($text) || empty($type)){
  echo '<span style="color: red;">  Todos os campos são obrigatórios </span>';
 }
 elseif ($image){
  $filename = stripslashes($_FILES['file']['name']);
  $extension = getExtension($filename);
  $extension = strtolower($extension);
  if (($extension != "jpg") && ($extension != "jpeg") && ($extension != "png") && ($extension != "gif")) {
   $change='<div class="msgdiv"> Extensão do ficheiro não reconhecida. </div> ';
   $errors=1;
  }
  else
  {
   $size=filesize($_FILES['file']['tmp_name']);
   if ($size > MAX_SIZE*1024){
   $change='<div class="msgdiv">Excedeu o limite do tamanho.</div> ';
   $errors=1;
   }
   if($extension=="jpg" || $extension=="jpeg" ){
 $uploadedfile = $_FILES['file']['tmp_name'];
 $src = imagecreatefromjpeg($uploadedfile);
   }
   else if($extension=="png")
   {
 $uploadedfile = $_FILES['file']['tmp_name'];
 $src = imagecreatefrompng($uploadedfile);
   }
   else
   {
 $src = imagecreatefromgif($uploadedfile);
   }
   echo $scr;
   list($width,$height)=getimagesize($uploadedfile);
   $newwidth=$width;
   $newheight=$height;
   $tmp=imagecreatetruecolor($newwidth,$newheight);
   imagecopyresampled($tmp,$src,0,0,0,0,$newwidth,$newheight,$width,$height);
   $filename = "../../images/". $_FILES['file']['name'];
   imagejpeg($tmp,$filename,100);
   imagedestroy($src);
   imagedestroy($tmp);
  }

  $nome_arquivo = $filename;
  $arquivo = explode('../../', $nome_arquivo);
  $picname = $arquivo[1];

  $insert = "UPDATE news
    SET title='".$title."', text='".$text."', type='".$type."', category='".$category."', img_news='".$picname."'
    WHERE id='".$_GET['id']."'";

  $insert_succ=mysql_query($insert) or die(mysql_error());

  if (!$insert_succ){
   echo 'Erro na atualização dos dados.';
  }

  if (mysql_affected_rows($connect) == 1)
  {
   header("Location:news.php");
  }
 }
}
elseif(($img['img_news']=='') && (empty($image) || empty($uploadedfile))){
 $insert = "UPDATE news
   SET title='".$title."', text='".$text."', type='".$type."', category='".$category."'
   WHERE id='".$_GET['id']."'";

 $insert_succ=mysql_query($insert) or die(mysql_error());

 if (!$insert_succ){
  echo 'Erro na atualização dos dados.';
 }

 if (mysql_affected_rows($connect) == 1)
 {
  header("Location:news.php");
 }
}
}
?>

O meu objetivo é fazer o update sempre. Por exemplo se a noticia ja tiver imagem e a input file estiver vazia ele faz update aos outros campos.

Posted (edited)

e qual é o problema?

Nunca cries duas variáveis com o mesmo nome, pode vir a causar problemas.

Acho que o teu problema está no mysql_affected_rows, pois tens lá uma variável $connect, que não a vejo no arquivo.

PS: E mais uma coisa, onde está a tua ligação á base de dados?

Edited by joaocasta
Posted

Ok, se calhar nao me expliquei muito bem.

Este codigo verifica se os campos estao vazios, se nao tiveramfaz o upload da imagem e edita todos os campos:

form:

<form method="post" action="" enctype="multipart/form-data" name="form1">
<div id="module-body">
<p>
<label>Título: </label>
<input type="text" class="input-long" style="width:300px;" name="title" value="<?php echo $row['title'] ?>" />
</p>
<p>
<label>Tipo: </label>
<input type="text" class="input-short" name="type" value="<?php echo $row['type'] ?>" />
</p>
<fieldset>
<?php
if($row['img_news']!=''){
?>
 <img src="../../<?php echo $row['img_news'] ?>" width="50">
 <label>Image:   </label><input size="25" name="file" type="file" style="font-family:Verdana, Arial, Helvetica, sans-serif; font-size:10pt" class="box"/>
<?php
}
else{
?>
<label>Image:   </label><input size="25" name="file" type="file" style="font-family:Verdana, Arial, Helvetica, sans-serif; font-size:10pt" class="box"/>
<?php 
}
?>
</fieldset>
<p>
<label>Categoria: </label>
<select class="input-short" name="category" >
<option value="Novidades">Novidades</option>
</select>
</p>
<p>
<label>Texto: </label>
<textarea rows="11" cols="90" name="texto"> <?php echo $row['text'] ?></textarea>
</p>
/* UPLOAD DA IMAGEM */
<div style="text-align: center;">
<input class="submit-green" type="submit" name="Submit" value="Submit" />
<input class="submit-gray" type="submit" value="Cancel" name="button_cancel_news" />
</div>
</form>

upload/update:

<?php
error_reporting(0);
$change="";
$abc="";
define ("MAX_SIZE","400");
function getExtension($str) {
$i = strrpos($str,".");
if (!$i) { return ""; }
$l = strlen($str) - $i;
$ext = substr($str,$i+1,$l);
return $ext;
}
$errors=0;
if($_SERVER["REQUEST_METHOD"] == "POST"){
$image =$_FILES["file"]['name'];
$uploadedfile = $_FILES['file']['tmp_name'];
$title = $_POST['title'];
$type = $_POST['type'];
$text = $_POST['texto'];
$category = $_POST['category'];

if (empty($image) || empty($uploadedfile) || empty($category) || empty($title) || empty($text) || empty($type)){
 echo '<span style="color: red;">  Todos os campos são obrigatórios </span>';
}
elseif ($image){
 $filename = stripslashes($_FILES['file']['name']);
 $extension = getExtension($filename);
 $extension = strtolower($extension);
 if (($extension != "jpg") && ($extension != "jpeg") && ($extension != "png") && ($extension != "gif")) {
  $change='<div class="msgdiv"> Extensão do ficheiro não reconhecida. </div> ';
  $errors=1;
 }
 else
 {
  $size=filesize($_FILES['file']['tmp_name']);
  if ($size > MAX_SIZE*1024){
  $change='<div class="msgdiv">Excedeu o limite do tamanho.</div> ';
  $errors=1;
  }
  if($extension=="jpg" || $extension=="jpeg" ){
   $uploadedfile = $_FILES['file']['tmp_name'];
   $src = imagecreatefromjpeg($uploadedfile);
  }
  else if($extension=="png")
  {
   $uploadedfile = $_FILES['file']['tmp_name'];
   $src = imagecreatefrompng($uploadedfile);
  }
  else
  {
   $src = imagecreatefromgif($uploadedfile);
  }
  echo $scr;
  list($width,$height)=getimagesize($uploadedfile);
  $newwidth=$width;
  $newheight=$height;
  $tmp=imagecreatetruecolor($newwidth,$newheight);
  imagecopyresampled($tmp,$src,0,0,0,0,$newwidth,$newheight,$width,$height);
  $filename = "../../images/". $_FILES['file']['name'];
  imagejpeg($tmp,$filename,100);
  imagedestroy($src);
  imagedestroy($tmp);
 }

 $nome_arquivo = $filename;
 $arquivo = explode('../../', $nome_arquivo);
 $picname = $arquivo[1];

 $insert = "UPDATE news
   SET title='".$title."', text='".$text."', type='".$type."', category='".$category."', img_news='".$picname."'
   WHERE id='".$_GET['id']."'";

 $insert_succ=mysql_query($insert) or die(mysql_error());

 if (!$insert_succ){
  echo 'Erro na atualização dos dados.';
 }

 if (mysql_affected_rows($connect) == 1)
 {
  header("Location:news.php");
 }
}
}
?>

O que eu quero fazer é: se ao abrir a cena de edição da noticia e a noticia ja tiver uma imagem ao clicar no botao ele verifica se a iinput da imagem ta vazio ou nao, se tiver vazio ele deixa passar (pois ja tem imagem), se nao tiver vazio altera a imagem.

Fui mais explicito?

Agradeço a vossa ajuda,

PF2G

Posted

Viva,

Está um pouco confuso o teu código...

O que te impede de usares apenas 2 condições:


if (!empty($_FILES)) {
   // Processar o upload da imagem etc...
   $picname = 'caminho_para_imagem';
}

if (!empty($_POST)) {
   // Processar o formulario etc...
}

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now
×
×
  • Create New...

Important Information

By using this site you accept our Terms of Use and Privacy Policy. We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.