Как я могу загрузить изображения на веб-сервер, в базу данных и отобразить изображение с помощью запроса? - PullRequest
0 голосов
/ 01 марта 2019

Я создаю своего рода систему управления запасами.Функциональность, над которой я сейчас работаю, - это добавление изображений инвентаря и другой информации в базу данных, веб-сервер и предоставление клиентской стороне текущего инвентаря с загруженными изображениями.В настоящее время я могу загружать изображения на веб-сервер только при добавлении новых ресурсов.Он добавляет строку в базу данных со всей вводимой информацией, кроме пути к файлу изображения, что не позволяет мне получить изображение и отобразить его на веб-странице.

Это php-файл для добавления нового инвентаря:

<?php 

//Add Apparel Form
echo "<div><h1>Add New Apparel</h1></div>";

    echo "<form action='addNewApparel.php' name='addApparel' enctype='multipart/form-data' method='post'>";

    echo "Select Category<span style='color:red'>*</span>: ";
    echo "<select name='category' required>";
        echo "<option value='' disabled selected></option>";
        echo "<option value='T-Shirt'>T-Shirt</option>";
        echo "<option value='Polo'>Polo</option>";
        echo "<option value='Button Up'>Button Up</option>";
        echo "<option value='1/4 Zip'>1/4 Zip</option>";
    echo "</select>";
    echo "<br>";
    echo "Description:<span style='color:red'>*</span> ";
    echo "<input type='textbox' name='description' required>";
    echo "<br>";
    echo "Cost:<span style='color:red'>*</span> $ ";
    echo "<input type='textbox' name='unitCost' placeholder='0.00' required>";
    echo "<br>";
    echo "XS Quantity: ";
    echo "<input type='number' name='xsQuantity' min = '0' value='0'>";
    echo "<br>";
    echo "S Quantity: ";
    echo "<input type='number' name='sQuantity' min = '0' value='0'>";
    echo "<br>";
    echo "M Quantity: ";
    echo "<input type='number' name='mQuantity' min = '0' value='0'>";
    echo "<br>";
    echo "L Quantity: ";
    echo "<input type='number' name='lQuantity' min = '0' value='0'>";
    echo "<br>";
    echo "XL Quantity: ";
    echo "<input type='number' name='xlQuantity' min = '0' value='0'>";
    echo "<br>";
    echo "XXL Quantity: ";
    echo "<input type='number' name='xxlQuantity' min = '0' value='0'>";
    echo "<br>";
    echo "XXXL Quantity: ";
    echo "<input type='number' name='xxxlQuantity' min = '0' value='0'>";
    echo "<br>";
    echo "<input type='file' name='apparelImage' onchange='loadFile(event)'>";
    echo "<img id='apparelImage' name='apparelImage' src='http://placehold.it/150/?           text=Choose+File' width='150' height='150'>";
    echo "<br><br>";
    echo "<input type='submit' id='submit' name='submit' value='Submit'>";

    echo "</form>";

    echo "<button><a href='addInventoryMenu.php'>Back</a></button>";

    //Connect to DB
    require_once("connect.php");

    //Define POST variables
    $category = $_POST["category"];
    $description = $_POST["description"];
    $unitCost = $_POST["unitCost"];
    $xsQuantity = $_POST["xsQuantity"];
    $sQuantity = $_POST["sQuantity"];
    $mQuantity = $_POST["mQuantity"];
    $lQuantity = $_POST["lQuantity"];
    $xlQuantity = $_POST["xlQuantity"];
    $xxlQuantity = $_POST["xxlQuantity"];
    $xxxlQuantity = $_POST["xxxlQuantity"];
    $newFileName= $_POST["apparelImage"];

    //Query to insert data into DB on form submission
    $query = "INSERT INTO `Apparel` (`category`, `description`, `unitCost`, `xsQuantity`, `sQuantity`, `mQuantity`, `lQuantity`, `xlQuantity`, `xxlQuantity`, `xxxlQuantity`, `apparelImage`) VALUES('".mysqli_real_escape_string($con, $category)."', '".mysqli_real_escape_string($con,$description)."', '$unitCost', '$xsQuantity', '$sQuantity', '$mQuantity', '$lQuantity', '$xlQuantity', '$xxlQuantity', '$xxxlQuantity', '$newFileName')";

    //Verify successful database connection and query execution
    $result = mysqli_query($con, $query);

    //Error Handling
    if($result) {
        echo "";
    } else {
        if (mysqli_connect_errno()){
            die("Unsuccessful connection to database: " . mysqli_connect_error());
        }
    }

    //Upload Images to Image Folder
    if(isset($_POST['submit'])) {
        $file = $_FILES['apparelImage']['file'];
        $fileName = $_FILES['apparelImage']['name'];
        $fileTmp = $_FILES['apparelImage']['tmp_name'];
        $fileError = $_FILES['apparelImage']['error'];
        $fileType = $_FILES['apparelImage']['type'];

        $fileExtension = explode('.', $fileName);
        $actualFileExtension = strtolower(end($fileExtension));

        $allowedExtensions = array('jpg', 'jpeg', 'png');

        if(in_array($actualFileExtension, $allowedExtensions)) {
            if ($fileError === 0) {
                $newFileName = uniqid('', true).".".$actualFileExtension;
                $fileDestination = '/export/home/business/'.$fileName;

                move_uploaded_file($fileTmp, $fileDestination);

                header("Location: addNewApparel.php?success");
            } else {
                echo "There was an error uploading your file.";
            }
        } else {
            echo "<br>";
            echo "Please upload a photo with a file name with an extension of .jpg, .jpeg, or .png.";
        }
    }

?>

Это php-файл для просмотра инвентаря:

    <?php
    //Connect to DB
    require_once("connect.php");

    //Query to display items
    $query = "SELECT * FROM `Apparel`";

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

    echo "<div><h1>Current Inventory</h1></div>";

    echo "<div>";
        echo "<a href='viewApparel.php'><button>Apparel</button></a>";
        echo "<a href='viewItems.php'><button>Items</button></a>";
        echo "<a href='viewMarketingMaterials.php'><button>Marketing Material</button></a>";
        echo "<button><a href='inventoryIndex.php'>Back</a></button>";  

    echo "</div>";
    echo "</table>";
    echo "<table border='1'>";
        echo "<tr>";
            echo "<th>Category</th>";
            echo "<th>Description</th>";
            echo "<th>Unit Cost</th>";
            echo "<th>XS Quantity</th>";
            echo "<th>S Quantity</th>";
            echo "<th>M Quantity</th>";
            echo "<th>L Quantity</th>";
            echo "<th>XL Quantity</th>";
            echo "<th>XXL Quantity</th>";
            echo "<th>XXXL Quantity</th>";
            echo "<th>Image</th>";
        echo "</tr>";

    while($row=mysqli_fetch_array($result)) {
        echo "<tr>";
            echo "<td>{$row['category']}</td>";
            echo "<td>{$row['description']}</td>";
            echo "<td>$ {$row['unitCost']}</td>";
            echo "<td>{$row['xsQuantity']}</td>";
            echo "<td>{$row['sQuantity']}</td>";
            echo "<td>{$row['mQuantity']}</td>";
            echo "<td>{$row['lQuantity']}</td>";
            echo "<td>{$row['xlQuantity']}</td>";
            echo "<td>{$row['xxlQuantity']}</td>";
            echo "<td>{$row['xxxlQuantity']}</td>";
            echo "<td><img src='{$row['apparelImage']}' width='150' height='150'></td>";
        echo "</tr>";
    }
    echo "</table>";

    echo "<button><a href='inventoryIndex.php'>Back</a></button>";

    //Error Handling
    if($result) {
        echo "";
    } else {
        if (mysqli_connect_errno()){
            die("Unsuccessful connection to database: " . mysqli_connect_error());
        }
    }
?>

Я знаю, что это много, но некоторая помощь была бы отличной, поскольку я почти уверен, что близок к тому, чтобы разобраться в этом!

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...