Ir para conteúdo

Arquivado

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

asacap1000

Update de anexos no banco

Recommended Posts

Galera tenho um relatório na qual é enviado anexos para o banco no insert ele trabalha desta forma segue script.

<?php
if (!empty($_FILES)) {
	$tempFile = $_FILES['arquivo']['tmp_name'];
	$pasta_dir = "../../../documentos/";
//Pega as Variaveis	
    $nome_arquivo = $_FILES['arquivo']['name'];
	$data = date("dmyhis");
	
//Junta todas as variaveis	
    $completo = $nome_arquivo;

//Pega a Extensão Original	
    $path_parts = pathinfo($nome_arquivo);

//Converte para MD5
	$nome_arquivo_md5 = md5($completo);
	
//Agora vai juntar nome em md5 com a extensão
    $nome_final =$nome_arquivo_md5.".".$path_parts['extension'];
		
//Pega o nome do arquivo com ele já modificado
	$targetFile =  str_replace('//','/',$pasta_dir) . $data.$nome_final;
	
 //move_uploaded_file($tempFile,$pasta_dir);
move_uploaded_file($tempFile,$targetFile);

$insert = "INSERT INTO tb_instrucao(anexos,tb_session, tb_dta, tb_cntr, tb_cliente, tb_movim, tb_espec, tb_temp, obs,tb_email) VALUES ('$targetFile','".$_SESSION['nome']."','$tb_dta', '$tb_cntr','".$_SESSION['nome']." ".$_SESSION['sobrenome']."','$tb_movim','$tb_espec','$tb_temp','$obs','$tb_email')";
mysql_query ($insert) or die (mysql_error() .'<BR><BR>ERRO - NÃO FOI POSSIVEL ENVIAR OS DADOS') ;

?>

A inserção está 100%, agora eu preciso criar uma tela na qual possa atualizar os dados e se precisar os anexos, no caso enviaria outro anexo. Da forma acima ele grava desta forma na base "../../../documentos/nomedoarquivo.pdf".

 

Agora para atualizar não consigo saír do lugar. segue o script da página de atualização. Se aguem puder me dar uma força.

<?php include ('../controle.php')?>
<?php require_once('Connections/controle.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"))
{
	if (!empty($_FILES)) {
	$tempFile = $_FILES['arquivo']['tmp_name'];
	$pasta_dir = "../../../documentos/";
//Pega as Variaveis	
    $nome_arquivo = $_FILES['arquivo']['name'];
	$data = date("dmyhis");
	
//Junta todas as variaveis	
    $completo = $nome_arquivo;

//Pega a Extensão Original	
    $path_parts = pathinfo($nome_arquivo);

//Converte para MD5
	$nome_arquivo_md5 = md5($completo);
	
//Agora vai juntar nome em md5 com a extensão
    $nome_final =$nome_arquivo_md5.".".$path_parts['extension'];
		
//Pega o nome do arquivo com ele já modificado
	$targetFile =  str_replace('//','/',$pasta_dir) . $data.$nome_final;
	
 //move_uploaded_file($tempFile,$pasta_dir);
move_uploaded_file($tempFile,$targetFile);
  $updateSQL = sprintf("UPDATE tb_instrucao SET anexos ='$targetFile', tb_dta=%s, tb_cntr=%s, tb_cliente=%s, tb_movim=%s, tb_espec=%s, tb_temp=%s, tb_status=%s, tb_correc=%s WHERE id=%s",
  					   $targetFile,
					   GetSQLValueString($_POST['tb_dta'], "text"),
                       GetSQLValueString($_POST['tb_cntr'], "text"),
                       GetSQLValueString($_POST['tb_cliente'], "text"),
                       GetSQLValueString($_POST['tb_movim'], "text"),
                       GetSQLValueString($_POST['tb_espec'], "text"),
                       GetSQLValueString($_POST['tb_temp'], "text"),
                       GetSQLValueString($_POST['tb_status'], "text"),
                       GetSQLValueString($_POST['tb_correc'], "text"),
                       GetSQLValueString($_POST['id'], "int"));

  mysql_select_db($database_controle, $controle);
  $Result1 = mysql_query($updateSQL, $controle) or die(mysql_error());

  $updateGoTo = "controle.php";
  if (isset($_SERVER['QUERY_STRING'])) {
    $updateGoTo .= (strpos($updateGoTo, '?')) ? "&" : "?";
    $updateGoTo .= $_SERVER['QUERY_STRING'];
  }
  header(sprintf("Location: %s", $updateGoTo));
}}

$colname_Recordset1 = "-1";
if (isset($_GET['id'])) {
  $colname_Recordset1 = $_GET['id'];
}
mysql_select_db($database_controle, $controle);
$query_Recordset1 = sprintf("SELECT * FROM tb_instrucao WHERE id = %s", GetSQLValueString($colname_Recordset1, "int"));
$Recordset1 = mysql_query($query_Recordset1, $controle) or die(mysql_error());
$row_Recordset1 = mysql_fetch_assoc($Recordset1);
$totalRows_Recordset1 = mysql_num_rows($Recordset1);
?>

<body>
<form action="<?php echo $editFormAction; ?>" method="post" name="form1" id="form1" enctype="multipart/form-data>

  <p align="left"><strong>Corrigir dados da Instrução</strong></p>
        <label><strong>Anexar Documentos</strong></label><br/>
	<input name="arquivo" id="arquivo" type="file" /> <strong>Enviar arquivo zipado se forem mais documentos</strong><br>

  <table align="left">
    <tr valign="baseline">
      <td nowrap="nowrap" align="right" valign="top">Documento:</td>
      <td><textarea name="tb_dta" cols="70" rows="2"><?php echo htmlentities($row_Recordset1['tb_dta'], ENT_COMPAT, 'utf-8'); ?></textarea></td>
    </tr>
    <tr valign="baseline">
      <td nowrap="nowrap" align="right">Conteiner:</td>
      <td><input type="text"  name="tb_cntr" value="<?php echo htmlentities($row_Recordset1['tb_cntr'], ENT_COMPAT, 'utf-8'); ?>" size="90" /></td>
    </tr>
    <tr valign="baseline">
      <td nowrap="nowrap" align="right">Cliente:</td>
      <td><input type="text" readonly name="tb_cliente" value="<?php echo htmlentities($row_Recordset1['tb_cliente'], ENT_COMPAT, 'utf-8'); ?>" size="70" /></td>
    </tr>
    <tr valign="baseline">
      <td nowrap="nowrap" align="right">Instrução:</td>
      <td><input type="text"  name="tb_movim" value="<?php echo htmlentities($row_Recordset1['tb_movim'], ENT_COMPAT, 'utf-8'); ?>" size="32" /></td>
    </tr>
    <tr valign="baseline">
      <td nowrap="nowrap" align="right"><div align="justify" dir="ltr">Refrigeração:</div></td>
      <td valign="baseline"><table width="198">
        <tr>
          <td><input type="radio"  name="tb_espec" value="SIM"<?php if (!(strcmp(htmlentities($row_Recordset1['tb_espec'], ENT_COMPAT, 'utf-8'),"SIM"))) {echo "checked=\"checked\"";} ?> />
            SIM</td>
          <td><input type="radio"  name="tb_espec" value="NAO" <?php if (!(strcmp(htmlentities($row_Recordset1['tb_espec'], ENT_COMPAT, 'utf-8'),"NAO"))) {echo "checked=\"checked\"";} ?> />
            NAO</td>
        </tr>
      </table></td>
    </tr>
    <tr valign="baseline">
      <td nowrap="nowrap" align="right">Temperatura:</td>
      <td><input type="text" name="tb_temp" value="<?php echo htmlentities($row_Recordset1['tb_temp'], ENT_COMPAT, 'utf-8'); ?>" size="32" /></td>
    </tr>
    <tr valign="baseline">
      <th nowrap="nowrap" align="right"><strong>Comentário</strong>:</th>
      <td><select size="1" name="tb_status" required>
      <option></option>
	<option>Dados verificados e Corrigidos</option>
	</select></td>
    </tr>
    </tr>
    <tr valign="baseline">
      <td nowrap="nowrap" align="right"> </td>
      <td><input type="submit" value="Atualizar Dados" /></td>
    </tr>
  </table>
  <input type="hidden" name="id" value="<?php echo $row_Recordset1['id']; ?>" />
  <input type="hidden" name="MM_update" value="form1" />
  <input type="hidden" name="id" value="<?php echo $row_Recordset1['id']; ?>" />
</form>
<p> </p>
</body>
</html>
<?php
mysql_free_result($Recordset1);
?>

Compartilhar este post


Link para o post
Compartilhar em outros sites

Que erro acontece?

 

(abandone o dreamwaver para seu proprio bem) :innocent:

do jeito que está este script não acontece erro algum porém não atualiza nenhum dado, não envia nenhum arquivo e não retornar para a página indicada após a atualização

 

 

O update acima foi criado com o dreamweaver, aguem teria uma forma mais prática para criar esta atualização de dados, se puderem me dar um exemplo, isso atualizando anexos tbm

 

 

Alguém??

Compartilhar este post


Link para o post
Compartilhar em outros sites

Veja se o upload esta acontecendo.

 

Olho arquivo de log do seu servidor ou habilite o display error no seu codigo.

if(move_uploaded_file($tempFile,$targetFile)){
echo 'arquivo movido';
}else
die('upload Error'.error_get_last()['message'] );

Compartilhar este post


Link para o post
Compartilhar em outros sites

interessante que mesmo colocando a mensagem de erro não aparecia nada,

Daí comecei a olhar o form se não faltava nada aí descobri.

Antes:

<form action="<?php echo $editFormAction; ?>" method="post" name="form1" id="form1" enctype="multipart/form-data>

 

Depois:

<form action="<?php echo $editFormAction; ?>" method="post" name="form1" id="form1" enctype="multipart/form-data">

 

A falta das Aspas duplas no final.

 

Valeww galera pela atenção

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.