dqh1992 2019-06-24 01:51
浏览 151
已采纳

在PHP和SQL中保存图像路径

I working on a project where I have a products table where I upload some images (3) for a each product. I am dealing with a problem to upload the files, because in the Database is only saving the dir and not the file . With this code an images I can explain it better. I just want to upload the file and save it the path, so i can later show it in the producto layout page and others.

Here is my HTML:

<div class="col form-group">
          <label class="form-label" for="imag1_prod"><b>Imagen 1: </b></label>
          <input type="file" class="filestyle" id="imag1_prod" name="imag1_prod" alt="Imagen del Producto 1" data-btnClass="btn-primary">
        </div>

I am working in a CRUD and I add the products through a Modal.

Next, My PHP: THE EDITED CODE

    <?php

require_once ("../paginas/conexion_bd.php"); //Contiene Funcion que Conecta a la Base de Datos

// escaping, additionally removing everything that could be (html/javascript-) code
if(isset($_FILES['imag1_prod']['name'])) {

//post variables
$ident_prod = mysqli_real_escape_string($con,(strip_tags($_POST["ident_prod"],ENT_QUOTES)));
$ident_cate = mysqli_real_escape_string($con,(strip_tags($_POST["ident_cate"],ENT_QUOTES)));
$nombr_prod = mysqli_real_escape_string($con,(strip_tags($_POST["nombr_prod"],ENT_QUOTES)));
$desco_prod = mysqli_real_escape_string($con,(strip_tags($_POST["desco_prod"],ENT_QUOTES)));
$desla_prod = mysqli_real_escape_string($con,(strip_tags($_POST["desla_prod"],ENT_QUOTES)));
$preci_prod = mysqli_real_escape_string($con,(strip_tags($_POST["preci_prod"],ENT_QUOTES)));
$pesoo_prod = mysqli_real_escape_string($con,(strip_tags($_POST["pesoo_prod"],ENT_QUOTES)));
$taman_prod = mysqli_real_escape_string($con,(strip_tags($_POST["taman_prod"],ENT_QUOTES)));
$stock_prod = mysqli_real_escape_string($con,(strip_tags($_POST["stock_prod"],ENT_QUOTES)));
$estad_prod = mysqli_real_escape_string($con,(strip_tags($_POST["estad_prod"],ENT_QUOTES)));


//get filename
$filename = $_FILES['imag1_prod']['name'];

//rename file
$temp = explode(".", $_FILES["imag1_prod"]["name"]);
$newfilename = round(microtime(true)) . '.' . end($temp);

//set path
$target_dir = "../imagen/productos/";

//upload files in folder
move_uploaded_file($_FILES['imag1_prod']['tmp_name'], "$target_dir/$newfilename");

//rename file with directory name
$filenamedirectory = $target_dir/$newfilename;

$statu_prod = 1;

    // Registrar en la Base de Datos
$sql = "INSERT INTO tabma_prod(ident_prod, ident_cate, nombr_prod, desco_prod, desla_prod, preci_prod, pesoo_prod, taman_prod, stock_prod, estad_prod, imag1_prod, statu_prod) VALUES ('$ident_prod',(SELECT ident_cate FROM tabma_cate WHERE ident_cate = '$ident_cate'),'$nombr_prod','$desco_prod','$desla_prod','$preci_prod','$pesoo_prod','$taman_prod','$stock_prod','$estad_prod','$filenamedirectory','$statu_prod') ";


    $query = mysqli_query($con,$sql);

    // Si ha sido Agregado Exitosamentee
    if ($query) {
        $messages[] = "El producto ha sido registrado con éxito.";
    } else {
        $errors[] = "Lo sentimos, el registro falló. Por favor, regrese y vuelva a intentarlo.";
    }
    }   

if (isset($errors)){        
    ?>
    <div class="alert alert-danger" role="alert">
        <button type="button" class="close" data-dismiss="alert">&times;</button>
            <strong>Error!</strong> 
            <?php
                foreach ($errors as $error) {
                        echo $error;
                    }
                ?>
    </div>
    <?php
    }
    if (isset($messages)){
        ?>
        <div class="alert alert-success" role="alert">
                <button type="button" class="close" data-dismiss="alert">&times;</button>
                <strong>¡Bien hecho!</strong>
                <?php
                    foreach ($messages as $message) {
                            echo $message;
                        }
                    ?>
        </div>
        <script type="text/javascript">
            $(".alert").delay(2000).slideUp(200, function() {
      $(this).alert('close');
    });
        </script>
        <?php
    }

It's designed to upload 3 images per product, but for now only one for testing.

Now, some images about how it looks and the errors:

Here the Errors that i get, dont know why undefined index if i am declaring as an

And here its what is already saving in the database:

As we can see, only saving the target_dir

Seeing this, the mistake has to be with the declaration of "imag1_prod" but i dont know why its wrong.

Hope can help me!

Best Regards to Everyone!

  • 写回答

1条回答 默认 最新

  • duanchique1196 2019-06-24 04:17
    关注

    The best practice is to save only directory and product name in the database and upload file to folder for later retrieval. So kudos for using good practices.

    As you've guessed, the problem is that your app is not recognizing the variable :

    $imag1_prod=$_FILES["imag1_prod"][ "name" ];
    

    Because you are renaming it here :

    move_uploaded_file($_FILES["imag1_prod"][" tmp_name "]
    

    The other issue here is that you are forgetting to store the filename as well as the directory.

    Try this :

    if(isset($_FILES['imag1_prod']['name'])) {
    
    //post variables
    $ident_prod = mysqli_real_escape_string($con,(strip_tags($_POST["ident_prod"],ENT_QUOTES)));
    $ident_cate = mysqli_real_escape_string($con,(strip_tags($_POST["ident_cate"],ENT_QUOTES)));
    $nombr_prod = mysqli_real_escape_string($con,(strip_tags($_POST["nombr_prod"],ENT_QUOTES)));
    $desco_prod = mysqli_real_escape_string($con,(strip_tags($_POST["desco_prod"],ENT_QUOTES)));
    $desla_prod = mysqli_real_escape_string($con,(strip_tags($_POST["desla_prod"],ENT_QUOTES)));
    $preci_prod = mysqli_real_escape_string($con,(strip_tags($_POST["preci_prod"],ENT_QUOTES)));
    $pesoo_prod = mysqli_real_escape_string($con,(strip_tags($_POST["pesoo_prod"],ENT_QUOTES)));
    $taman_prod = mysqli_real_escape_string($con,(strip_tags($_POST["taman_prod"],ENT_QUOTES)));
    $stock_prod = mysqli_real_escape_string($con,(strip_tags($_POST["stock_prod"],ENT_QUOTES)));
    $estad_prod = mysqli_real_escape_string($con,(strip_tags($_POST["estad_prod"],ENT_QUOTES)));
    
    
    //get filename
    $filename = $_FILES['imag1_prod']['name'];
    
    //rename file
    $temp = explode(".", $_FILES["imag1_prod"]["name"]);
    $newfilename = round(microtime(true)) . '.' . end($temp);
    
    //set path
    $target_dir = "../imagen/productos/";
    
    //upload files in folder
    move_uploaded_file($_FILES['imag1_prod']['tmp_name'], "$target_dir/$newfilename");
    
    //rename file with directory name
    $filenamedirectory = $target_dir/$newfilename;
    
    $statu_prod = 1;
    
    // Registrar en la Base de Datos
    $sql = "INSERT INTO tabma_prod(ident_prod, ident_cate, nombr_prod, desco_prod, desla_prod, preci_prod, pesoo_prod, taman_prod, stock_prod, estad_prod, imag1_prod, statu_prod) 
    VALUES ('$ident_prod',(SELECT ident_cate FROM tabma_cate WHERE ident_cate = '$ident_cate'),'$nombr_prod','$desco_prod','$desla_prod','$preci_prod','$pesoo_prod','$taman_prod','$stock_prod','$estad_prod','$filenamedirectory','$statu_prod') ";
    }
    

    Also make sure you use prepared statement to avoid SQL injections when performing database operations.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 乌班图ip地址配置及远程SSH
  • ¥15 怎么让点阵屏显示静态爱心,用keiluVision5写出让点阵屏显示静态爱心的代码,越快越好
  • ¥15 PSPICE制作一个加法器
  • ¥15 javaweb项目无法正常跳转
  • ¥15 VMBox虚拟机无法访问
  • ¥15 skd显示找不到头文件
  • ¥15 机器视觉中图片中长度与真实长度的关系
  • ¥15 fastreport table 怎么只让每页的最下面和最顶部有横线
  • ¥15 java 的protected权限 ,问题在注释里
  • ¥15 这个是哪里有问题啊?