PHP MySQL 使用表单上传与所有属性链接的图片

PHP MySQL Upload image linked with all properties using form

这是我的表单代码,用于将新产品添加到我的 table 'items' 数据库中。

                <form method="post" action="additem.php">
                    Product name: <input method="text" name="itemName" class="field">
                    Size: <select name="sizes" class="field">
                        <option value="XS">XS</option>
                        <option value="S">S</option>
                        <option value="M">M</option>
                        <option value="L">L</option>
                        <option value="XL">XL</option>
                    </select>
                    Gender: <select name="gender" class='field'>
                        <option value="Male">Male</option>
                        <option value="Female">Female</option>
                        <option value="Kids">Kids clothing</option>
                    </select>
                    Price: <input method="text" name="price" class="field">
                    Image: 'Your code here'
                    <input type="submit" class="btn">
                </form>

Php 用于将数据从表单插入到 table 'items' 的代码。用户输入要添加的项目的所有属性并应上传图像文件。当用户点击提交按钮时,php 代码将被处理。

<?php

$link = mysqli_connect('localhost', 'root', '', 'onlinestorebd');
$itemName=mysqli_real_escape_string($link, $_POST['itemName']);
$itemSize=mysqli_real_escape_string($link,$_POST['sizes']);
$price=mysqli_real_escape_string($link, $_POST['price']);
$gender=mysqli_real_escape_string($link, $_POST['gender']);
$itemPhoto=mysqli_real_escape_string($link,$_POST['itemPhoto']);
$mysqli = new mysqli("localhost", "root", "", "onlinestorebd");
$qq="INSERT INTO items (itemName, sizes, gender, price, itemPhoto) VALUES ('".$itemName."','".$itemSize."', '".$gender."', '".$price."','".$itemPhoto."')";
$result=$mysqli->query($qq);




mysqli_close($mysqli);



IF(!$result){
    echo "Data insert failed <br><br>";
    echo mysql_error();
    
} ELSE {

    echo "Item has been added";
    echo "<br><br><a href=\"editdb.php\">Back to products list</a>";
    
}

?>

首先你必须为带有表单元素的图像添加一个参数。

您的代码

<form method="post" action="additem.php">

新代码

 <form method="post" action="additem.php" enctype="multipart/form-data">

然后检查您的 php.ini 文件

file_uploads = On

最后一步

<?php
$target_dir = "uploads/";
$target_file = $target_dir . basename($_FILES["file"]["name"]);
$uploadOk = 1;
$imageFileType = strtolower(pathinfo($target_file,PATHINFO_EXTENSION));
// Check if image file is a actual image or fake image
if(isset($_POST["submit"])) {
  $check = getimagesize($_FILES["file"]["tmp_name"]);
  if($check !== false) {
    echo "File is an image - " . $check["mime"] . ".";
    $uploadOk = 1;
  } else {
    echo "File is not an image.";
    $uploadOk = 0;
  }
}
?>