Ir para conteúdo
Fórum Script Brasil
  • 0

Inserir Imagens Em Um Banco Mysql


Guest - Caio -

Pergunta

Eu estou construindo um site de uma imobiliaria o qual tem uma página de inserção de registros. Gostaria de saber como faço para a foto ser inserida corretamente pois eu não estou conseguindo exibi-la posteriormente, é feito o upload para o servidor porém acho que as informações que vão para o campo foto são insuficientes para localizar a foto na pasta do servidor.

Suegue o código:

<?php
function GetSQLValueString($theValue, $theType, $theDefinedValue = "", $theNotDefinedValue = "") 
{
  $theValue = (!get_magic_quotes_gpc()) ? addslashes($theValue) : $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_insert"])) && ($_POST["MM_insert"] == "form1")) {
  $arquivo = $_FILES["foto"];
$arquivo_nome = $arquivo["name"];
$endereco = "c:\inetpub\wwwroot\perfilimoveisonline\dados";
$tudo = $endereco + $arquivo_nome; 
  $insertSQL = sprintf("INSERT INTO imoveis (codneg, cod_tipo, local_cod, Área, Condomínio, Cidade, Bairro, Dormitórios, Valor, Detalhes, foto) VALUES (%s, %s, %s, %s, %s, %s, %s, %s, %s, %s, '$arquivo_nome')",
                       GetSQLValueString($_POST['codneg'], "int"),
                       GetSQLValueString($_POST['cod_tipo'], "int"),
                       GetSQLValueString($_POST['local_cod'], "int"),
                       GetSQLValueString($_POST['Área'], "text"),
                       GetSQLValueString($_POST['Condominio'], "text"),
                       GetSQLValueString($_POST['Cidade'], "text"),
                       GetSQLValueString($_POST['Bairro'], "text"),
                       GetSQLValueString($_POST['Dormitorios'], "int"),
                       GetSQLValueString($_POST['Valor'], "text"),
                       GetSQLValueString($_POST['Detalhes'], "text"));
                      
set_time_limit(0);
$diretorio = "c:\inetpub\wwwroot\perfilimoveisonline\dados";
$id_arquivo = "foto";
$nome_arquivo = $_FILES[$id_arquivo]["name"];
$arquivo_temporario = $_FILES[$id_arquivo]["tmp_name"];
move_uploaded_file($arquivo_temporario, "$diretorio/$nome_arquivo");
                       

  mysql_select_db($database_conexao, $conexao);
  $Result1 = mysql_query($insertSQL, $conexao) or die(mysql_error());

  $insertGoTo = "SUCESSO.PHP";
  if (isset($_SERVER['QUERY_STRING'])) {
    $insertGoTo .= (strpos($insertGoTo, '?')) ? "&" : "?";
    $insertGoTo .= $_SERVER['QUERY_STRING'];
  }
  header(sprintf("Location: %s", $insertGoTo));
}
?>
especificamente:
if ((isset($_POST["MM_insert"])) && ($_POST["MM_insert"] == "form1")) {
  $arquivo = $_FILES["foto"];
$arquivo_nome = $arquivo["name"];
$endereco = "c:\inetpub\wwwroot\perfilimoveisonline\dados";
$tudo = $endereco + $arquivo_nome; 
  $insertSQL = sprintf("INSERT INTO imoveis (codneg, cod_tipo, local_cod, Área, Condomínio, Cidade, Bairro, Dormitórios, Valor, Detalhes, foto) VALUES (%s, %s, %s, %s, %s, %s, %s, %s, %s, %s, '$arquivo_nome')",
                       GetSQLValueString($_POST['codneg'], "int"),
                       GetSQLValueString($_POST['cod_tipo'], "int"),
                       GetSQLValueString($_POST['local_cod'], "int"),
                       GetSQLValueString($_POST['Área'], "text"),
                       GetSQLValueString($_POST['Condominio'], "text"),
                       GetSQLValueString($_POST['Cidade'], "text"),
                       GetSQLValueString($_POST['Bairro'], "text"),
                       GetSQLValueString($_POST['Dormitorios'], "int"),
                       GetSQLValueString($_POST['Valor'], "text"),
                       GetSQLValueString($_POST['Detalhes'], "text"));
                      
set_time_limit(0);
$diretorio = "c:\inetpub\wwwroot\perfilimoveisonline\dados";
$id_arquivo = "foto";
$nome_arquivo = $_FILES[$id_arquivo]["name"];
$arquivo_temporario = $_FILES[$id_arquivo]["tmp_name"];
move_uploaded_file($arquivo_temporario, "$diretorio/$nome_arquivo");
                       

  mysql_select_db($database_conexao, $conexao);
  $Result1 = mysql_query($insertSQL, $conexao) or die(mysql_error());

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

Valeu! wink.gif

Link para o comentário
Compartilhar em outros sites

3 respostass a esta questão

Posts Recomendados

  • 0

de boa veio , cadastre-se ai podemos te ajudar melhor smile.gif .

cadastre-se e seja mais um da familia scriptbrasil smile.gif

Isso vai te ajudar muito cara . Qualquer coisa estamos ai pro que der e vier . smile.gif

upload.php

<html>

<head>

</head>

<body bgcolor='#FFFFFF'>

<form name='frm_files' method='post' enctype='multipart/form-data' action='envia.php'>

  <table border='0' cellpading='0' cellspacing='0' width='90%'>

  <tr>

  <td width='10%'>Título</td>

  <td width='80%'><input type='text' class="caixa_verde" name='txt_titulo' size='25'></td>

  </tr>

 

  <tr>

  <td width='10%'>Foto:&nbsp;</td>

  <td width='80%'><input type='file' class="caixa_verde" name='txt_foto' size='20' ></td>

  </tr>

  </table>

  <input type='submit' name='btnOK' value='Enviar'>

</form>

</body>

</html>

envia.php

<?

include "config.php";

//RECEBE OS DADOS DO FORMULÁRIO

$titulo = $_POST["txt_titulo"];

//RECEBE OS DADOS DO CAMPO $_FILES

$foto_temp = $_FILES["txt_foto"]["tmp_name"]; //CAMINHO TEMPORÁRIO

$foto_name = $_FILES["txt_foto"]["name"];  //NOME DO ARQUIVO

$foto_size = $_FILES["txt_foto"]["size"];  //TAMANHO DO ARQUIVO

$foto_type = $_FILES["txt_foto"]["type"];  //TIPO DO ARQUIVO

//EXIBINDO OS DADOS

echo "<h3>ENVIANDO O ARQUIVO ...</h3>";

echo "titulo =  ".$titulo."<br>";

echo "NOME DO ARQUIVO = ".$foto_name."<br>";

echo "TAMANHO DO ARQUIVO = ".$foto_size."<br>";

//ENVIA O ARQUIVO PARA A PASTA

if(!copy($foto_temp, "fotos/$foto_name")) {

echo "Aconteceu algum erro !!!";

}

else {

$x = mysql_query("INSERT INTO imagem_fotolog (tópico,imagem) VALUES ('$titulo','$foto_name')");

if(!$x){

echo "Erro ao tentar incluir registro: ".mysql_error();

}

else{

echo "OK";

}

}

?>

Link para o comentário
Compartilhar em outros sites

Participe da discussão

Você pode postar agora e se registrar depois. Se você já tem uma conta, acesse agora para postar com sua conta.

Visitante
Responder esta pergunta...

×   Você colou conteúdo com formatação.   Remover formatação

  Apenas 75 emoticons são permitidos.

×   Seu link foi incorporado automaticamente.   Exibir como um link em vez disso

×   Seu conteúdo anterior foi restaurado.   Limpar Editor

×   Você não pode colar imagens diretamente. Carregar ou inserir imagens do URL.



  • Estatísticas dos Fóruns

    • Tópicos
      152,2k
    • Posts
      652,1k
×
×
  • Criar Novo...