我如何获得提交的“;新产品“;通过我的表单,这样我就可以重命名与它一起提交的图像


How do i get the id of a submitted "new product" through my form, so i can rename an image submitted with it?

这是我的代码,图像被上传到我想要的地方,但每次都被命名为0。"文件扩展名",但我希望图像的名称与我使用此表单提交的对象的id相同。id:3img名称:3."文件扩展名"
我的php:

<?php
if (isset($_POST['submit_newProduct'])) { // Form has been submitted.
    $errors = array();
    // perform validations on the form data and avoid sql injection

    $product_name = trim(mysqli_real_escape_string($connection, $_POST['product_name']));
    $product_price = trim(mysqli_real_escape_string($connection, $_POST['product_price']));
    $product_desc = trim(mysqli_real_escape_string($connection, $_POST['product_desc']));
    $product_category = trim(mysqli_real_escape_string($connection, $_POST['product_category']));
    $product_attribute = trim(mysqli_real_escape_string($connection, $_POST['product_attribute']));
    $query = "INSERT INTO products
              (product_name, product_price, product_desc, 
               product_category, product_attribute)
             VALUES ('{$product_name}', '{$product_price}', 
                     '{$product_desc}', '{$product_category}', 
                     '{$product_attribute}')";
    $filename = $_FILES["product_img"]["name"];
    $file_basename = substr($filename, 0, strripos($filename, '.')); // get file extention
    $file_ext = substr($filename, strripos($filename, '.')); // get file name
    $filesize = $_FILES["product_img"]["size"];
    $allowed_file_types = array('.png','.jpg','.jpeg','.gif');
    if (in_array($file_ext,$allowed_file_types) && ($filesize < 200000)) {
        // Rename file
        $pid = mysqli_insert_id($connection);
        $newfilename = $pid . $file_ext;
        if (file_exists("img/product_img/" . $newfilename))
        {
            // file already exists error
            echo "You have already uploaded this file.";
        }
        else
        {
            move_uploaded_file($_FILES["product_img"]["tmp_name"], "img/product_img/" . $newfilename);
            echo "File uploaded successfully.";
        }
    }
    elseif (empty($file_basename))
    {
        // file selection error
        echo "Please select a file to upload.";
    }
    elseif ($filesize > 200000)
    {
        // file size error
        echo "The file you are trying to upload is too large.";
    }
    else
    {
        // file type error
        echo "Only these file typs are allowed for upload: " . implode(', ',$allowed_file_types);
        unlink($_FILES["file"]["tmp_name"]);
    }
    header("location:product_list.php"); //maskes sure item is not recreated on refresh

    $result = mysqli_query($connection, $query);
    if ($result) {
        $message = "Produkt oprettet.";
    } else {
        $message = "Der skete en fejl";
        $message .= "<br />" . mysqli_error($connection);
    }
}
?>


我的html表单:

<form action="" method="post" enctype="multipart/form-data">
        <div class="col-md-6">
          <h4>Produkt navn</h4>
          <input type="text" name="product_name" class="form-control"> <br>
          <h4>Produkt pris</h4>
          <input type="text" placeholder="DKK" name="product_price" class="form-control" style="width:30%;"><br>
          <h4>Produkt beskrivelse</h4>
          <textarea type="text" name="product_desc" rows="3" class="form-control"></textarea> <br>
          <h4>Produkt kategori</h4>
            <select name="product_category" class="form-control">
                <option></option>
                <option>Gummi ænder</option>
                <option>Påklædning</option>
                <option>Accessories</option>
            </select> <br>
            <h4>Produkt attribut</h4>
            <input type="text" name="product_attribute" class="form-control" value=""> <br>
          <input type="file" name="product_img"><br>
          <input type="submit" name="submit_newProduct" class="btn btn-warning pull-right" value="Tilføj produkt">
        </div>
      </form>

由于查询在mysqli_insert_id()之后执行;这就是它返回0的原因。将您的查询放在mysqli_insert_id(之前),则只有您才能获得inserted id

我挡住了你的去路。您可以相应地更改它。

<?php
if (isset($_POST['submit_newProduct'])) { // Form has been submitted.
    $errors = array();
    // perform validations on the form data and avoid sql injection
    $product_name = trim(mysqli_real_escape_string($connection, $_POST['product_name']));
    $product_price = trim(mysqli_real_escape_string($connection, $_POST['product_price']));
    $product_desc = trim(mysqli_real_escape_string($connection, $_POST['product_desc']));
    $product_category = trim(mysqli_real_escape_string($connection, $_POST['product_category']));
    $product_attribute = trim(mysqli_real_escape_string($connection, $_POST['product_attribute']));
    $query = "INSERT INTO products (product_name, product_price, product_desc, product_category, product_attribute)
             VALUES ('{$product_name}', '{$product_price}', '{$product_desc}', '{$product_category}', '{$product_attribute}')";
        $result = mysqli_query($connection, $query);
        if ($result) {
                $filename = $_FILES["product_img"]["name"];
                $file_basename = substr($filename, 0, strripos($filename, '.')); // get file extention
                $file_ext = substr($filename, strripos($filename, '.')); // get file name
                $filesize = $_FILES["product_img"]["size"];
                $allowed_file_types = array('.png','.jpg','.jpeg','.gif');
                if (in_array($file_ext,$allowed_file_types) && ($filesize < 200000)) {
                    // Rename file
                    $pid = mysqli_insert_id($connection);
                    $newfilename = $pid . $file_ext;
                    if (file_exists("img/product_img/" . $newfilename)){
                        // file already exists error
                        echo "You have already uploaded this file.";
                    } else {
                        move_uploaded_file($_FILES["product_img"]["tmp_name"], "img/product_img/" . $newfilename);
                        echo "File uploaded successfully.";
                    }
                }
                elseif (empty($file_basename)){
                    // file selection error
                    echo "Please select a file to upload.";
                }
                elseif ($filesize > 200000){
                    // file size error
                    echo "The file you are trying to upload is too large.";
                }
                else{
                    // file type error
                    echo "Only these file typs are allowed for upload: " . implode(', ',$allowed_file_types);
                    unlink($_FILES["file"]["tmp_name"]);
                }
                $message = "Produkt oprettet.";
        }
        else {
            $message = "Der skete en fejl";
      $message .= "<br />" . mysqli_error($connection);
        }
    header("location:product_list.php"); //maskes sure item is not recreated on refresh
}
?>