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

Upload de imagem gravando no banco de dados


Portal do Químico

Pergunta

Boa tarde a todos, estou com um problema ao gravar a imagem no banco de dados. Na verdade o script nem chega a funcionar.

Vou dividir o tópico em 2: O Como está meu script ATUAL e como foi minha tentativa:

SCRIPT ATUAL:

<?php require_once('../../Connections/#.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']);
}
function converter_data($strData) {
    // Recebemos a data no formato: dd/mm/aaaa
    // Convertemos a data para o formato: aaaa-mm-dd
    if ( preg_match("#/#",$strData) == 1 ) {
        $strDataFinal = "'";
        $strDataFinal .= implode('-', array_reverse(explode('/',$strData)));
        $strDataFinal .= "'";
    }
    return $strDataFinal;
}

if ((isset($_POST["MM_insert"])) && ($_POST["MM_insert"] == "form1")) {
  $insertSQL = sprintf("INSERT INTO site_noticias (not_titulo, not_imagem, not_descricao, not_texto, not_categoria, not_autor, not_fonte, not_status, not_data) VALUES (%s, %s, %s, %s, %s, %s, %s, %s, %s)",
                       GetSQLValueString($_POST['not_titulo'], "text"),
                       GetSQLValueString($_POST['not_imagem'], "text"),
                       GetSQLValueString($_POST['not_descricao'], "text"),
                       GetSQLValueString($_POST['not_texto'], "text"),
                       GetSQLValueString($_POST['not_categoria'], "text"),
                       GetSQLValueString($_POST['not_autor'], "text"),
                       GetSQLValueString($_POST['not_fonte'], "text"),
                       GetSQLValueString(isset($_POST['not_status']) ? "true" : "", "defined","1","0"),
                       converter_data($_POST['not_data']));

  mysql_select_db($database_gwb_connect, $gwb_connect);
  $Result1 = mysql_query($insertSQL, $gwb_connect) or die(mysql_error());

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

mysql_select_db($database_gwb_connect, $gwb_connect);
$query_rs_categorias = "SELECT * FROM site_categoria_noticia";
$rs_categorias = mysql_query($query_rs_categorias, $gwb_connect) or die(mysql_error());
$row_rs_categorias = mysql_fetch_assoc($rs_categorias);
$totalRows_rs_categorias = mysql_num_rows($rs_categorias);
?>
FORMULARIO
<form action="<?php echo $editFormAction; ?>" method="post" name="form1" id="form1">
  <table align="center">
      <tr>
      <td colspan="2" class="table_header_left">TITULO</td>
    </tr>
    <tr valign="baseline">
      <td colspan="2" align="left" nowrap="nowrap"><input type="text" name="not_titulo" value="" size="105" /></td>
    </tr>
        <tr>
      <td colspan="2" class="table_header_left">IMAGEM</td>
    </tr>
    <tr valign="baseline">
      <td colspan="2" align="left" nowrap="nowrap">
        <!-- <input type="text" name="not_imagem" value="" size="32" />
        <select name="not_imagem">
<?php
    // lista as pastas se houverem
    if ($arquivos != "" ) {
        foreach($arquivos as $listar)
       {  ?>
      <option value="<?php echo "$caminho/$listar"; ?>" selected="selected"><?php echo $listar;?></option>
<?php
        }  
   }
?>
    </select>-->
    <input type="file" name="not_imagem" /><br /><br />
    </td>
      </tr>
            <tr>
      <td colspan="2" class="table_header_left">DESCRIÇÃO</td>
    </tr>
    <tr valign="baseline">
      <td colspan="2" align="left" valign="top" nowrap="nowrap">
        <textarea name="not_descricao" cols="50" rows="5"></textarea></td>
      </tr>
    <tr>
      <td colspan="2" class="table_header_left">CORPO DA NOTÍCIA</td>
    </tr>
    <tr valign="baseline">
      <td colspan="2" align="right" valign="top" nowrap="nowrap">
        <textarea name="not_texto" cols="50" rows="5"></textarea></td>
      </tr>
    <tr valign="baseline">
      <td width="55" align="left" nowrap="nowrap">Categoria:</td>
      <td width="571" align="left"><select name="not_categoria">
        <?php 
do {  
?>
        <option value="<?php echo $row_rs_categorias['cat_nome']?>" ><?php echo $row_rs_categorias['cat_nome']?></option>
        <?php
} while ($row_rs_categorias = mysql_fetch_assoc($rs_categorias));
?>
      </select></td>
    </tr>
    <tr valign="baseline">
      <td nowrap="nowrap" align="left">Autor:</td>
      <td align="left"><input type="text" name="not_autor" value="" size="32" /></td>
    </tr>
    <tr valign="baseline">
      <td nowrap="nowrap" align="left">Fonte:</td>
      <td align="left"><input type="text" name="not_fonte" value="" size="32" /></td>
    </tr>
    <tr valign="baseline">
      <td align="left" nowrap="nowrap">Status:</td>
      <td align="left"><input type="checkbox" name="not_status" value="" /></td>
    </tr>
    <tr valign="baseline">
      <td nowrap="nowrap" align="left">Data:</td>
      <td align="left"><input name="not_data" type="text" value="<?php 
$dia = date(d); 
$mes = date(m); 
$ano = date(Y);
echo "$dia/$mes/$ano";
?>" size="32" /></td>
    </tr>
    <tr valign="baseline">
      <td nowrap="nowrap" align="right"> </td>
      <td><input type="submit" value="Cadastrar" />
        <input name="Reset" type="reset" value="Limpar" /></td>
    </tr>
  </table>
  <input type="hidden" name="MM_insert" value="form1" />
</form>
<?php
mysql_free_result($rs_categorias);
?>
Como tentei
<?php require_once('../../Connections/#.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']);
}
function converter_data($strData) {
    // Recebemos a data no formato: dd/mm/aaaa
    // Convertemos a data para o formato: aaaa-mm-dd
    if ( preg_match("#/#",$strData) == 1 ) {
        $strDataFinal = "'";
        $strDataFinal .= implode('-', array_reverse(explode('/',$strData)));
        $strDataFinal .= "'";
    }
    return $strDataFinal;
}

if ($_POST['cadastrar']) {
    
    // Recupera os dados dos campos
    $imagem = $_FILES["not_imagem"];
    
    // Se a foto estiver sido selecionada
    if (!empty($imagem["name"])) {
        
        // Largura máxima em pixels
        $largura = 150;
        // Altura máxima em pixels
        $altura = 180;
        // Tamanho máximo do arquivo em bytes
        $tamanho = 1000;

        // Verifica se o arquivo é uma imagem
        if(!eregi("^image\/(pjpeg|jpeg|png|gif|bmp)$", $imagem["type"])){
            $error[1] = "Isso não é uma imagem.";
            } 
    
        // Pega as dimensões da imagem
        $dimensoes = getimagesize($imagem["tmp_name"]);
    
        // Verifica se a largura da imagem é maior que a largura permitida
        if($dimensoes[0] > $largura) {
            $error[2] = "A largura da imagem não deve ultrapassar ".$largura." pixels";
        }

        // Verifica se a altura da imagem é maior que a altura permitida
        if($dimensoes[1] > $altura) {
            $error[3] = "Altura da imagem não deve ultrapassar ".$altura." pixels";
        }
        
        // Verifica se o tamanho da imagem é maior que o tamanho permitido
        if($arquivo["size"] > $tamanho) {
                $error[4] = "A imagem deve ter no máximo ".$tamanho." bytes";
        }

        // Se não houver nenhum erro
        if (count($error) == 0) {
        
            // Pega extensão da imagem
            preg_match("/\.(gif|bmp|png|jpg|jpeg){1}$/i", $imagem["name"], $ext);

            // Gera um nome único para a imagem
            $nome_imagem = md5(uniqid(time())) . "." . $ext[1];

            // Caminho de onde ficará a imagem
            $caminho_imagem = "fotos/" . $nome_imagem;

            // Faz o upload da imagem para seu respectivo caminho
            move_uploaded_file($imagem["tmp_name"], $caminho_imagem);
        
            // Insere os dados no banco
             $insertSQL = sprintf("INSERT INTO site_noticias (not_titulo, not_imagem, not_descricao, not_texto, not_categoria, not_autor, not_fonte, not_status, not_data) VALUES (%s, %s, %s, %s, %s, %s, %s, %s, %s)",
                       GetSQLValueString($_POST['not_titulo'], "text"),
                       GetSQLValueString($imagem, "text"),
                       GetSQLValueString($_POST['not_descricao'], "text"),
                       GetSQLValueString($_POST['not_texto'], "text"),
                       GetSQLValueString($_POST['not_categoria'], "text"),
                       GetSQLValueString($_POST['not_autor'], "text"),
                       GetSQLValueString($_POST['not_fonte'], "text"),
                       GetSQLValueString(isset($_POST['not_status']) ? "true" : "", "defined","1","0"),
                       converter_data($_POST['not_data']));

        
            // Se os dados forem inseridos com sucesso
            if ($insertSQL){
                echo "Você foi cadastrado com sucesso.";
            }
        }
    
        // Se houver mensagens de erro, exibe-as
        if (count($error) != 0) {
            foreach ($error as $erro) {
                echo $erro . "<br />";
            }
        }
    }
}

// if ((isset($_POST["MM_insert"])) && ($_POST["MM_insert"] == "form1")) { 

  mysql_select_db($database_gwb_connect, $gwb_connect);
  $Result1 = mysql_query($insertSQL, $gwb_connect) or die(mysql_error());

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

mysql_select_db($database_gwb_connect, $gwb_connect);
$query_rs_categorias = "SELECT * FROM site_categoria_noticia";
$rs_categorias = mysql_query($query_rs_categorias, $gwb_connect) or die(mysql_error());
$row_rs_categorias = mysql_fetch_assoc($rs_categorias);
$totalRows_rs_categorias = mysql_num_rows($rs_categorias);
?>

alguém tem alguma ideia do que eu posso fazer pra consertar essa script?

Desde já agradeço!

Editado por Portal do Químico
Link para o comentário
Compartilhar em outros sites

8 respostass a esta questão

Posts Recomendados

  • 0

FIT, boa tarde.

Então, a página nem exibe. Fica toda em branco.

Fiz a seguinte modificação e consegui inserir o nome do arquivo no banco de dados, mas o arquivo não faz upload pra pasta que foi settada.

<?php require_once('/Connections/gwb_connect.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']);
}
function converter_data($strData) {
    // Recebemos a data no formato: dd/mm/aaaa
    // Convertemos a data para o formato: aaaa-mm-dd
    if ( preg_match("#/#",$strData) == 1 ) {
        $strDataFinal = "'";
        $strDataFinal .= implode('-', array_reverse(explode('/',$strData)));
        $strDataFinal .= "'";
    }
    return $strDataFinal;
}
if ($_POST['cadastrar']) {
    
    // Recupera os dados dos campos
    //$nome = $_POST['nome'];
    //$email = $_POST['email'];
    $foto = $_FILES["not_imagem"];
    
    // Se a foto estiver sido selecionada
    if (!empty($foto["name"])) {
        
        // Largura máxima em pixels
        $largura = 15000;
        // Altura máxima em pixels
        $altura = 18000;
        // Tamanho máximo do arquivo em bytes
        $tamanho = 100000;

        // Verifica se o arquivo é uma imagem
        if(!eregi("^image\/(pjpeg|jpeg|png|gif|bmp)$", $foto["type"])){
            $error[1] = "Isso não é uma imagem.";
            } 
    
        // Pega as dimensões da imagem
        $dimensoes = getimagesize($foto["tmp_name"]);
    
        // Verifica se a largura da imagem é maior que a largura permitida
        if($dimensoes[0] > $largura) {
            $error[2] = "A largura da imagem não deve ultrapassar ".$largura." pixels";
        }

        // Verifica se a altura da imagem é maior que a altura permitida
        if($dimensoes[1] > $altura) {
            $error[3] = "Altura da imagem não deve ultrapassar ".$altura." pixels";
        }
        
        // Verifica se o tamanho da imagem é maior que o tamanho permitido
        if($arquivo["size"] > $tamanho) {
                $error[4] = "A imagem deve ter no máximo ".$tamanho." bytes";
        }

        // Se não houver nenhum erro
        if (count($error) == 0) {
        
            // Pega extensão da imagem
            preg_match("/\.(gif|bmp|png|jpg|jpeg){1}$/i", $foto["name"], $ext);

            // Gera um nome único para a imagem
            $nome_imagem = md5(uniqid(time())) . "." . $ext[1];

            // Caminho de onde ficará a imagem
            $caminho_imagem = "images/" . $nome_imagem;

            // Faz o upload da imagem para seu respectivo caminho
            move_uploaded_file($foto["tmp_name"], $caminho_imagem);
                
            // Se os dados forem inseridos com sucesso
            if ($insertSQL){
            echo "Você foi cadastrado com sucesso.";
            }
        }
    
        // Se houver mensagens de erro, exibe-as
        if (count($error) != 0) {
            foreach ($error as $erro) {
                echo $erro . "<br />";
            }
        }
    }
}

if ((isset($_POST["MM_insert"])) && ($_POST["MM_insert"] == "form1")) {
  $insertSQL = sprintf("INSERT INTO site_noticias (not_titulo, not_imagem, not_descricao, not_texto, not_categoria, not_autor, not_fonte, not_status, not_data) VALUES (%s, %s, %s, %s, %s, %s, %s, %s, %s)",
                       GetSQLValueString($_POST['not_titulo'], "text"),
                       GetSQLValueString($_POST['not_imagem'], "text"),
                       GetSQLValueString($_POST['not_descricao'], "text"),
                       GetSQLValueString($_POST['not_texto'], "text"),
                       GetSQLValueString($_POST['not_categoria'], "text"),
                       GetSQLValueString($_POST['not_autor'], "text"),
                       GetSQLValueString($_POST['not_fonte'], "text"),
                       GetSQLValueString(isset($_POST['not_status']) ? "true" : "", "defined","1","0"),
                       converter_data($_POST['not_data']));  

  mysql_select_db($database_gwb_connect, $gwb_connect);
  $Result1 = mysql_query($insertSQL, $gwb_connect) or die(mysql_error());

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

mysql_select_db($database_gwb_connect, $gwb_connect);
$query_rs_categorias = "SELECT * FROM site_categoria_noticia";
$rs_categorias = mysql_query($query_rs_categorias, $gwb_connect) or die(mysql_error());
$row_rs_categorias = mysql_fetch_assoc($rs_categorias);
$totalRows_rs_categorias = mysql_num_rows($rs_categorias);
?>

Então FIT. Dessa forma consigo registrar o nome do arquivo no banco de dados, mas me parece que a função pra fazer upload do arquivo não funciona.

Aguardo uma resposta!

Link para o comentário
Compartilhar em outros sites

  • 0

Cara vou passar aqui pra você um script que eu fiz para Upload de imagens com o banco, ta bem mais simples, inclusive eu não utilizo duas páginas pra fazer POST em php eu utilizo tudo sempre na mesma, fica bem melhor, da uma estudada no meu código que você vai entender... Lembrando que o sistema esta para interagir com MySQL, esta também com filtro de segurança para strings maliciosas, nome de imagens incompativeis e tipo de arquivo. Como eu não uso o mysql_real_escape_strin(); pra passar o código de MySQL para MSSQL é só mudar as funções de 'mysql' para 'mssql'.

*OBS: Esse tipo de action do form faz ele chamar a própria página e o campo hidden que tem no form faz a verificação lá em cima com o PHP pra ver se o form foi submetido e assim a gente mata a necessidade de duas páginas pra um form funcionar, o código inteiro esta completo e pronto, não falta nada....

<?php 
$padrao1  = "/[']/";
$padrao2 = "/[)]/";
$padrao3 = "/[(]/";
$replace1 = "''";
$replace2 = "";

$conHost = mysql_connect('host','user','pass');
$selectDb = mysql_select_db('db',$conHost);

if($_POST['cmdEnviarImg'] == "cmdIr"){
    
    $defImgLargura = 1400;
    $defImgAltura = 1400;
    $defImgBytes = 2048000;
    
    
    $formCategoria = $_POST['formCategoria'];
    $formDescr = $_POST['formDescr'];
    $formDescr = preg_replace($padrao1,$replace1,$formDescr);
    $formImgName = $_FILES['formImg']['name'];
    $formImgName = preg_replace($padrao1,$replace1,$formImgName);
    $formImgName = preg_replace($padrao2,$replace2,$formImgName);
    $formImgName = preg_replace($padrao3,$replace2,$formImgName);
    
    $formImgTmp = $_FILES['formImg']['tmp_name'];
    
    
    if(!empty($formImgName)){
        $formImgSize = getimagesize($formImgTmp);
    }
    
    
    $formImgType = $_FILES['formImg']['type'];
    $formImgBytes = $_FILES['formImg']['size'];
    $formImgLargura = $formImgSize[0];
    $formImgAltura = $formImgSize[1];
    $imgType = substr($formImgName, -3);
    
    $cmdSelectSegImg = "SELECT * FROM tableImagem WHERE imagemName = '".$formImgName."'";
        
    $querySelectSegImg = mysql_query($cmdSelectSegImg);
    
    $arraySelectSegImg = mysql_fetch_array($querySelectSegImg);
    
    $dbIdSeg = $arraySelectSegImg['I1_ID'];
    
    $qtCaracteres = strlen($formImgName) - 4;
    
    if(strlen($formImgName) > 54){
        $erroDb = "<div align='left' id='div' style='background-color:#FF9393; color:#C60000; padding-left:5px; padding-top:5px; padding-bottom:5px; padding-right:5px;'><img src='../images/aviso.png' width='14' height='14' /> Esta imagem tem o nome muito grande para ser inserida. A o nome desta imagem possui <strong>".$qtCaracteres."</strong> caracteres, o máximo de caracteres que uma imagem deve possuir é <strong>50</strong> caracteres</div><br>";
    }
    
    if(!empty($dbIdSeg)){
        $erroDb = "<div align='left' id='div' style='background-color:#FF9393; color:#C60000; padding-left:5px; padding-top:5px; padding-bottom:5px; padding-right:5px;'><img src='../images/aviso.png' width='14' height='14' /> Você já possuí uma imagem com o nome <strong>".$formImgName."</strong>, por favor renomeie a imagem e insira novamente.</div><br>";
    }
    
    
    if(empty($formDescr)){
        $erroDescr = "<div align='left' id='div' style='background-color:#FF9393; color:#C60000; padding-left:5px; padding-top:5px; padding-bottom:5px; padding-right:5px;'><img src='../images/aviso.png' width='14' height='14' />  Você deve inserir uma <strong>descrição</strong> para a imagem</div><br>";
    }
    
    if(($imgType != "png") && ($imgType != "jpg") && ($imgType != "jpeg") && ($imgType != "gif") && ($imgType != "bmp") && ($imgType != "PNG") && ($imgType != "JPG") && ($imgType != "JPEG") && ($imgType != "GIF") && ($imgType != "BMP")){
        $erroImgType = "<div align='left' id='div' style='background-color:#FF9393; color:#C60000; padding-left:5px; padding-top:5px; padding-bottom:5px; padding-right:5px;'><img src='../images/aviso.png' width='14' height='14' />   Arquivo em formato inválido! A imagem deve ser <strong>jpg</strong>, <strong>jpeg</strong>, 
            <strong>bmp</strong>, <strong>gif</strong> ou <strong>png</strong>. Envie outro arquivo</div><br>";
    }
    
    if(($formImgLargura > $defImgLargura) || ($formImgAltura > $defImgAltura)){
        $erroImgSize = "<div align='left' id='div' style='background-color:#FF9393; color:#C60000; padding-left:5px; padding-top:5px; padding-bottom:5px; padding-right:5px;'><img src='../images/aviso.png' width='14' height='14' /> Os valores máximos e largura e altura são <strong>".$defImgLargura."x".$defImgAltura."</strong>, você esta tentando enviar <strong>".$formImgLargura."x".$formImgAltura."</strong></div><br>";
    }
    
    if($formImgBytes > $defImgBytes){
        $erroImgBytes = "<div align='left' id='div' style='background-color:#FF9393; color:#C60000; padding-left:5px; padding-top:5px; padding-bottom:5px; padding-right:5px;'><img src='../images/aviso.png' width='14' height='14' /> O tamanho máximo em Bytes que a imagem deve possuir é <strong>".$defImgBytes."</strong>, a imagem que você inseriu possui <strong>".$formImgBytes."</strong></div><br>";
    }
    
    if((empty($erroImgBytes)) && (empty($erroImgSize)) && (empty($erroImgType)) && (empty($erroDescr)) && (empty($erroDb))){
        
        $tailInsertImg = "(imagemName, imagemData, imagemCategoria, imagemTipo, imagemSize, imagemDescr) VALUES ('".$_FILES['formImg']['name']."','".date ("Ymd")."','".$formCategoria."','".$_FILES['formImg']['type']."','".$_FILES['formImg']['size']."','".$formDescr."')";
        
        $cmdInsertImg = "INSERT INTO tableImagem ".$tailInsertImg;
        
        $queryInsertImg = mysql_query($cmdInsertImg);
        
        $imgName = $_FILES['formImg']['name'];
        
        // Caminho de onde a imagem ficará
        $imgDir = "../../imgUpload/" . $imgName;

        // Faz o upload da imagem
        move_uploaded_file($_FILES['formImg']['tmp_name'], $imgDir);

        $msgFinalizar = "<div align='center' style='background-color:#AAFFAA; color:#009900; padding-left:5px; padding-top:5px; padding-bottom:5px; padding-right:5px;'>Sua imagem foi enviada com sucesso!</div><br>";
        $formDescr = "";
        
    }
    
}


?>
<?php if((!empty($erroImgBytes)) || (!empty($erroImgSize)) || (!empty($erroImgType)) || (!empty($erroDescr)) || (!empty($erroDb)) || (!empty($msgFinalizar))){
    
    echo "<fieldset><legend style='font-size:24px;'>Aviso!</legend>";
    
     ?>
<?php echo "".$erroDb.""; ?>
<?php echo "".$msgFinalizar.""; ?>
<?php echo "".$erroImgBytes.""; ?>
<?php echo "".$erroImgSize.""; ?>
<?php echo "".$erroDescr.""; ?>
<?php echo "".$erroImgType.""; ?>
<?php echo "</fieldset>"; ?>
<?php } ?>

<fieldset>
<legend style="font-size:24px;"> Upload de imagem</legend>
<form method="post" enctype="multipart/form-data">
<input type="hidden" name="cmdEnviarImg" value="cmdIr" />
<table width="500">
    <tr>
        <td width="86">Galeria:</td>
        <td width="402">
        <select name="formCategoria">
           
        <option value="1">Categoria 1</option>
        <option value="2">Categoria 2</option>
        <option value="3">Categoria 3</option>
        
        </select>
        </td>
    </tr>
    <tr>
        <td width="86">Imagem:</td>
        <td width="402"> <input type="file" name="formImg" /></td>
    </tr>
    <tr>
        <td width="86">Descrição:</td>
        <td width="402"><textarea name="formDescr" cols="60" rows="5"><?php echo $formDescr; ?></textarea></td>
    </tr>
    <tr>
        <td colspan="2" align="center"><input type="submit" name="Submit" onclick="this.disabled=true; this.value = 'Aguarde…'; this.form.submit();" value="Enviar imagem" /></td>
    </tr>
</table>
</form>
</fieldset>

E lembre-se de acesso 777 para as pastas que irão receber as imagens

Link para o comentário
Compartilhar em outros sites

  • 0

FIT, nada cara... O form com isto não grava nem a informação no banco de dados.

Vou ser + prático:

Tenho 2 scripts funcionais: A script de upload c/ gravação do campo imagem no banco de dados e a SCRIPT que foi criada com o dream weaver.

<?php
// Conexão com o banco de dados
$conn = @mysql_connect("localhost", "root", "###") or die ("Problemas na conexão.");
$db = @mysql_select_db("portal_gwb###", $conn) or die ("Problemas na conexão");

// Se o usuário clicou no botão cadastrar efetua as ações
if ($_POST['cadastrar']) {
    
    // Recupera os dados dos campos
    //$nome = $_POST['nome'];
    //$email = $_POST['email'];
    $foto = $_FILES["foto"];
    
    // Se a foto estiver sido selecionada
    if (!empty($foto["name"])) {
        
        // Largura máxima em pixels
        $largura = 15000;
        // Altura máxima em pixels
        $altura = 18000;
        // Tamanho máximo do arquivo em bytes
        $tamanho = 1000000;

        // Verifica se o arquivo é uma imagem
        if(!eregi("^image\/(pjpeg|jpeg|png|gif|bmp)$", $foto["type"])){
            $error[1] = "Isso não é uma imagem.";
            } 
    
        // Pega as dimensões da imagem
        $dimensoes = getimagesize($foto["tmp_name"]);
    
        // Verifica se a largura da imagem é maior que a largura permitida
        if($dimensoes[0] > $largura) {
            $error[2] = "A largura da imagem não deve ultrapassar ".$largura." pixels";
        }

        // Verifica se a altura da imagem é maior que a altura permitida
        if($dimensoes[1] > $altura) {
            $error[3] = "Altura da imagem não deve ultrapassar ".$altura." pixels";
        }
        
        // Verifica se o tamanho da imagem é maior que o tamanho permitido
        if($arquivo["size"] > $tamanho) {
                $error[4] = "A imagem deve ter no máximo ".$tamanho." bytes";
        }

        // Se não houver nenhum erro
        if (count($error) == 0) {
        
            // Pega extensão da imagem
            preg_match("/\.(gif|bmp|png|jpg|jpeg){1}$/i", $foto["name"], $ext);

            // Gera um nome único para a imagem
            $nome_imagem = $foto["name"];

            // Caminho de onde ficará a imagem
            $caminho_imagem = "images/" . $nome_imagem;

            // Faz o upload da imagem para seu respectivo caminho
            move_uploaded_file($foto["tmp_name"], $caminho_imagem);
        
            // Insere os dados no banco
            $sql = mysql_query("INSERT INTO site_noticias (not_imagem) VALUES ('".$nome_imagem."')");
        
            // Se os dados forem inseridos com sucesso
            if ($sql){
                echo "Você foi cadastrado com sucesso.";
            }
        }
    
        // Se houver mensagens de erro, exibe-as
        if (count($error) != 0) {
            foreach ($error as $erro) {
                echo $erro . "<br />";
            }
        }
    }
}
?>
<form action="<?php echo $_SERVER['PHP_SELF'] ?>" method="post" enctype="multipart/form-data" name="cadastro" >
Imagem:<br />
<input type="file" name="foto" /><br /><br />
<input type="submit" name="cadastrar" value="Cadastrar" />
</form>
Essa script acima funciona perfeitamente, envia o arquivo e grava no banco de dados o nome da imagem. Porem eu tenho uma página de cadastro de notícia pronta e iria inserir apenas um campo FILE pra poder fazer tudo em um arquivo apenas. O problema parece estar na forma que estou unindo essas funções. alguém please, me da um help de como unir a script acima com essa:
<?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']);
}
function converter_data($strData) {
    // Recebemos a data no formato: dd/mm/aaaa
    // Convertemos a data para o formato: aaaa-mm-dd
    if ( preg_match("#/#",$strData) == 1 ) {
        $strDataFinal = "'";
        $strDataFinal .= implode('-', array_reverse(explode('/',$strData)));
        $strDataFinal .= "'";
    }
    return $strDataFinal;
}

if ((isset($_POST["MM_insert"])) && ($_POST["MM_insert"] == "form1")) {
  $insertSQL = sprintf("INSERT INTO site_noticias (not_titulo, not_imagem, not_descricao, not_texto, not_categoria, not_autor, not_fonte, not_status, not_data) VALUES (%s, %s, %s, %s, %s, %s, %s, %s, %s)",
                       GetSQLValueString($_POST['not_titulo'], "text"),
                       GetSQLValueString($_POST['not_imagem'], "text"),
                       GetSQLValueString($_POST['not_descricao'], "text"),
                       GetSQLValueString($_POST['not_texto'], "text"),
                       GetSQLValueString($_POST['not_categoria'], "text"),
                       GetSQLValueString($_POST['not_autor'], "text"),
                       GetSQLValueString($_POST['not_fonte'], "text"),
                       GetSQLValueString(isset($_POST['not_status']) ? "true" : "", "defined","1","0"),
                       converter_data($_POST['not_data']));

  mysql_select_db($database_gwb_connect, $gwb_connect);
  $Result1 = mysql_query($insertSQL, $gwb_connect) or die(mysql_error());

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

mysql_select_db($database_gwb_connect, $gwb_connect);
$query_rs_categorias = "SELECT * FROM site_categoria_noticia";
$rs_categorias = mysql_query($query_rs_categorias, $gwb_connect) or die(mysql_error());
$row_rs_categorias = mysql_fetch_assoc($rs_categorias);
$totalRows_rs_categorias = mysql_num_rows($rs_categorias);
?>

Meu conhecimento em PHP + MySQL é muito limitado ao dreamweaver. Ainda vou estudar, se possivel não mande o codigo pronto, explique o devo fazer (Passo-a-Passo)

Obrigado

OBS: O nome do campo FILE é not_imagem, portanto onde se lê foto, considere not_imagem!

Editado por Portal do Químico
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
      152k
    • Posts
      651,8k
×
×
  • Criar Novo...