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 HFSS 中的 H 场图与 MATLAB 中绘制的 B1 场 部分对应不上
  • ¥15 如何在scanpy上做差异基因和通路富集?
  • ¥20 关于#硬件工程#的问题,请各位专家解答!
  • ¥15 关于#matlab#的问题:期望的系统闭环传递函数为G(s)=wn^2/s^2+2¢wn+wn^2阻尼系数¢=0.707,使系统具有较小的超调量
  • ¥15 FLUENT如何实现在堆积颗粒的上表面加载高斯热源
  • ¥30 截图中的mathematics程序转换成matlab
  • ¥15 动力学代码报错,维度不匹配
  • ¥15 Power query添加列问题
  • ¥50 Kubernetes&Fission&Eleasticsearch
  • ¥15 報錯:Person is not mapped,如何解決?