0

I have been working on this script for a while and I am trying to add data into the products table. The challenge I am having is that the script runs and returns a success message that the data was added but the table in the database will be empty. It does save the picture in the products folder but does not upload the data to the table. Where am I missing my mistake?

add-product.php

<form action="includes/functions.inc.php" method="post" class="d-flex flex-wrap" enctype="multipart/form-data">
                <section class="w-25 p-3">
                    <label for="shop-id" class="title">Shop ID</label>
                    <select name="shopID" id="shop-id" class="form-input">
                    <?php
                        $shops = "SELECT * FROM shops";
                        $shopResults = mysqli_query($conn, $shops);

                        if (mysqli_num_rows($shopResults)) {
                            while ($shop = mysqli_fetch_assoc($shopResults)) {
                    ?>
                        <option value="<?php echo $shop['id'] ?>"><?php echo $shop['shopName'] ?></option>
                    <?php
                            }
                        } else {
                    ?>
                        <option>No shops found</option>
                    <?php
                        }
                    ?>
                    </select>
                </section>
                <section class="w-25 p-3">
                    <label for="shop-type" class="title">Type</label>
                    <select name="shopType" id="shop-type" class="form-input">
                        <option value="product">Product</option>
                        <option value="service">Service</option>
                    </select>
                </section>
                <section class="w-25 p-3">
                    <label for="name" class="title">Product Name</label>
                    <input type="text" name="productName" id="name" class="form-input">
                </section>
                <section class="w-25 p-3">
                    <label for="price" class="title">Product Price</label>
                    <input type="text" name="price" id="price" class="form-input">
                </section>
                <section class="w-25 p-3">
                    <label for="color" class="title">Product Colors</label>
                    <input type="text" name="color" id="color" class="form-input">
                </section>
                <section class="w-25 p-3">
                    <label for="size" class="title">Product Sizes</label>
                    <input type="text" name="size" id="size" class="form-input">
                </section>
                <section class="w-25 p-3">
                    <label for="import" class="title">Import</label>
                    <select name="import" id="import" class="form-input">
                        <option value="1">Yes</option>
                        <option value="0">No</option>
                    </select>
                </section>
                <section class="w-25 p-3">
                    <label for="pre-order" class="title">Pre-Order</label>
                    <select name="preOrder" id="pre-order" class="form-input">
                        <option value="1">Yes</option>
                        <option value="0">No</option>
                    </select>
                </section>
                <section class="w-50 p-3">
                    <label for="short-desc" class="title">Product Short Description</label>
                    <textarea name="shortDesc" id="short-desc" cols="30" rows="10" class="form-input"></textarea>
                </section>
                <section class="w-50 p-3">
                    <label for="description" class="title">Product Description</label>
                    <textarea name="description" id="description" cols="30" rows="10" class="form-input"></textarea>
                </section>
                <section class="w-25 p-3">
                    <label for="tags" class="title">Product Tags</label>
                    <input type="text" name="tags" id="tags" class="form-input">
                </section>
                <section class="w-25 p-3">
                    <label for="deliveryTime" class="title">Product Delivery Time</label>
                    <input type="text" name="deliveryTime" id="deliveryTime" class="form-input">
                </section>
                <section class="w-25 p-3">
                    <label for="stock" class="title">Product Stock</label>
                    <input type="text" name="stock" id="stock" class="form-input">
                </section>
                <section class="w-25 p-3">
                    <label for="discount" class="title">Product Discount</label>
                    <input type="text" name="discount" id="discount" class="form-input">
                </section>
                <section class="w-50 p-3">
                    <label for="image" class="title">Main Image</label>
                    <input type="file" name="image" id="image" class="form-input">
                </section>
                <section class="w-50 p-3">
                    <label for="images" class="title">Additional Images</label>
                    <input type="file" name="images[]" id="images" class="form-input" multiple>
                </section>
                <section class="w-100 text-center mt-3">
                    <button type="submit" class="btn btn-default" name="add-product">Add</button>
                </section>
            </form>

functions.inc.php

 if (isset($_POST['add-product'])) {

        $shopName = mysqli_real_escape_string($conn, $_POST['shopID']);
        $type = mysqli_real_escape_string($conn, $_POST['shopType']);
        $productName = mysqli_real_escape_string($conn, $_POST['productName']);
        $productPrice = mysqli_real_escape_string($conn, $_POST['price']);
        $productColor = mysqli_real_escape_string($conn, $_POST['color']);
        $productShortDescription = mysqli_real_escape_string($conn, $_POST['shortDesc']);
        $productDescription = mysqli_real_escape_string($conn, $_POST['description']);
        $productSize = mysqli_real_escape_string($conn, $_POST['size']);
        $productTag = mysqli_real_escape_string($conn, $_POST['tags']);
        $productImport = mysqli_real_escape_string($conn, $_POST['import']);
        $productDeliveryTime = mysqli_real_escape_string($conn, $_POST['deliveryTime']);
        $productStock = mysqli_real_escape_string($conn, $_POST['stock']);
        $reg_date = date('Y-m-d H:i:s');

        $productImage = $_FILES['image'];

        if(empty($shopName) || empty($type) || empty($productName) || empty($productPrice) || empty($productColor) || empty($productShortDescription) || empty($productDescription) || empty($productSize) || empty($productTag) || empty($productImage) || empty($productDeliveryTime) || empty($productStock) || empty($productImport) || empty($productOrder)) {
            header('Location: ../admin/products.php?error=emptyFields');
        } else if (empty($shopName)) {
            header('Location: ../admin/products.php?error=emptyShopName');
        } else if (empty($type)) {
            header('Location: ../admin/products.php?error=emptyType');
        } else if (empty($productName)) {
            header('Location: ../admin/products.php?error=emptyName');
        } else if (empty($productPrice)) {
            header('Location: ../admin/products.php?error=emptyPrice');
        } else if (empty($productColor)) {
            header('Location: ../admin/products.php?error=emptyColor');
        } else if (empty($productShortDescription)) {
            header('Location: ../admin/products.php?error=emptyShortDescription');
        } else if (empty($productDescription)) {
            header('Location: ../admin/products.php?error=emptyDescription');
        } else if (empty($productSize)) {
            header('Location: ../admin/products.php?error=emptySize');
        } else if (empty($productTag)) {
            header('Location: ../admin/products.php?error=emptyTags');
        } else if (empty($productImage)) {
            header('Location: ../admin/products.php?error=emptyImage');
        } else if (empty($productImport)) {
            header('Location: ../admin/products.php?error=importEmpty');
        } else if (empty($productStock)) {
            header('Location: ../admin/products.php?error=stockEmpty');
        } else if (!preg_match('/^[a-zA-Z0-9 \s \- \_ \']*$/', $productName)) {
            header('Location: ../admin/products.php?error=invalidNames');
        } else if (!preg_match('/^[0-9 \.]*$/', $productPrice)) {
            header('Location: ../admin/products.php?error=invalidPrice');
        } else if (!preg_match('/^[a-zA-Z0-9 \, \s]*$/', $productColor)) {
            header('Location: ../admin/products.php?error=invalidColors');
        } else if (!preg_match('/^[a-zA-Z0-9 \, \s]*$/', $productSize)) {
            header('Location: ../admin/products.php?error=invalidSizes');
        } else if (!preg_match('/^[a-zA-Z0-9 \, \s]*$/', $productTag)) {
            header('Location: ../admin/products.php?error=invalidTags');
        } else {
            $a = count($_FILES['images']['name']);

            $allowed = array('jpg', 'png', 'jpeg', 'webp');

            for ($i = 0; $i < $a; $i++) {
                $file_name = $_FILES["images"]["name"][$i];
                $file_type = $_FILES["images"]["type"][$i];
                $file_tempName = $_FILES["images"]["tmp_name"][$i];
                $file_error = $_FILES["images"]["error"][$i];
                $file_size = $_FILES["images"]["size"][$i];

                $fileExt = explode('.', $file_name);
                $fileActualExt = strtolower(end($fileExt));

                if (in_array($fileActualExt, $allowed)) {
                    if ($file_error === 0) {
                        if ($file_size <= 15000000) {

                            $newFileName = preg_replace('/\s+/', '', $productName) . $i . '.' . $fileActualExt;
                            $fileDestination = '../../products/' . $newFileName;

                            $sql = "INSERT INTO product_images (shopID, product_name, image_path) VALUES (?,?,?)";
                            $stmt = mysqli_stmt_init($conn);

                            if (!mysqli_stmt_prepare($stmt, $sql)) {
                                header("Location: ../admin/products.php?error=SaveError");
                            } else {
                                mysqli_stmt_bind_param($stmt, 'sss', $shopName, $productName, $newFileName);
                                mysqli_stmt_execute($stmt);
                            }

                            move_uploaded_file($file_tempName = $_FILES["images"]["tmp_name"][$i], $fileDestination);
                        } else {
                            header('Location: ../admin/products.php?error=invalidSize');
                        }
                    } else {
                        header('Location: ../admin/products.php?error=invalidImage');
                    }
                } else {
                    header('Location: ../admin/products.php?error=invalidImageTypes');
                }
            }
            $imageName = $_FILES['image']['name'];
            $imageType = $_FILES['image']['type'];
            $imageTempName = $_FILES['image']['tmp_name'];
            $imageError = $_FILES['image']['error'];
            $imageSize = $_FILES['image']['size'];

            $fileExt = explode('.', $imageName);
            $fileActualExt = strtolower(end($fileExt));

            $allowed = array('jpg', 'png', 'jpeg', 'webp');

            if (in_array($fileActualExt, $allowed)) {
                if ($imageError === 0) {
                    if ($imageSize <= 15000000) {
                        $newFileName = preg_replace('/\s+/', '', $productName) . '.' . $fileActualExt;
                        $fileDestination = '../../products/' . $newFileName;

                        $sql = "INSERT INTO products (shopID, product_type, product_name, product_price, product_size, product_color, product_shortDesc, product_description, product_tags,  product_image, product_deliveryTime, product_stock, product_import, product_preorder, reg_date) VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)";
                        $stmt = mysqli_stmt_init($conn);
                        if (!mysqli_stmt_prepare($stmt, $sql)) {
                            header("Location: ../admin/products.php?error=SaveError");
                            exit();
                        } else {
                            mysqli_stmt_bind_param($stmt, 'sssssssssssssss', $shopName, $type, $productName, $productPrice, $productSize, $productColor, $productShortDescription, $productDescription, $productTag, $newFileName, $productDeliveryTime, $productStock, $product_import, $product_preorder, $reg_date);
                            mysqli_stmt_execute($stmt);

                            move_uploaded_file($imageTempName, $fileDestination);
                            header("Location: ../../admin/products.php?success");
                            exit();
                        }
                    } else {
                        header('Location: ../admin/products.php?error=invalidSize');
                        exit();
                    }
                } else {
                    header('Location: ../admin/products.php?error=invalidImage');
                    exit();
                }
            } else {
                header('Location: ../admin/products.php?error=invalidImageType');
                exit();
            }
        }
    }

table in database

$productsTable = "CREATE TABLE IF NOT EXISTS products (
    id INT(11) NOT NULL AUTO_INCREMENT PRIMARY KEY,
    shopID INT(11) NOT NULL,
    product_type VARCHAR(7) NOT NULL,
    product_name VARCHAR(500) NOT NULL,
    product_price FLOAT NOT NULL,
    product_size VARCHAR(255) NOT NULL,
    product_color VARCHAR(500) NOT NULL,
    product_shortDesc VARCHAR(500) NOT NULL,
    product_description VARCHAR(2000) NOT NULL,
    product_tags VARCHAR(1000) NOT NULL,
    product_image VARCHAR(600) NOT NULl,
    product_deliveryTime VARCHAR(10) NOT NULL,
    product_discount INT(3) NOT NULL,
    product_stock INT(5) NOT NULL,
    product_status VARCHAR(25) NOT NULL,
    product_import VARCHAR(3) NOT NULL,
    product_preorder VARCHAR(3) NOT NULL,
    reg_date TIMESTAMP DEFAULT CURRENT_TIMESTAMP
)";
$productsQuery = mysqli_query($conn, $productsTable);
  • 1
    You aren't checking whether `mysqli_stmt_bind_param` or `mysqli_stmt_execute` succeeds, or checking what the error is if they don't – ADyson Jan 05 '21 at 18:46
  • 2
    Do not use `mysqli_real_escape_string` – Dharman Jan 05 '21 at 18:49
  • 1
    You need to stop manually checking for errors. Please read: [Should we ever check for mysqli_connect() errors manually?](https://stackoverflow.com/q/58808332/1839439) and [Should I manually check for errors when calling “mysqli_stmt_prepare”?](https://stackoverflow.com/q/62216426/1839439) – Dharman Jan 05 '21 at 18:49

0 Answers0