简体   繁体   中英

php script upload only the first image to database

I have the form where you need to upload some pictures, but when I upload pictures in the uploader, only the first picture is saved. I don't know where is the problem. Thank you so much for your time and help.

PHP

Here is the php script which is add picture to my database

session_start();

include '../../include/config.php';

// Create random name
function generateRandomString($length = 25) {
    $characters = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
    $randomString = '';
    for ($i = 0; $i < $length; $i++) {
        $randomString .= $characters[rand(0, strlen($characters) - 1)];
    }
    return $randomString;
}

// Upload product image
$productimg = generateRandomString();
$allowedExts = array("gif", "jpeg", "jpg", "png");

$temp = explode(".", $_FILES["pimage"]["name"]);
$extension = end($temp);

$productimg = $productimg . "." . $extension;
move_uploaded_file($_FILES["pimage"]["tmp_name"],
"../../images/products/" . $productimg);


// Add product image
$sqlImage = "INSERT INTO productimages (pid, pimage) VALUES (" . $_REQUEST['pid'] . ",'" . $productimg . "')";

try{
    $queryimg = $db->prepare($sqlImage);

    $queryimg->execute();
    }
    catch(PDOException $ecop) {
        die($ecop->getMessage());
    }


//Select new default image
$sqlNewImage = "SELECT * FROM productimages WHERE pid=" . $_REQUEST['pid'];
try{
    $query = $db->query($sqlNewImage);

    $query->setFetchMode(PDO::FETCH_ASSOC);

    $row = $query->fetch();

    if ($query->rowCount() > 0) { 

        $newIMG = $row['pimage'];

    }else
    {
        $newIMG = "default.png";
    }
    }
    catch(PDOException $e) {
        die($e->getMessage());
    }
$sqlUpdateImage = "UPDATE products SET pimage = '" . $newIMG . "' WHERE id = " . $_REQUEST['pid'];

try{
    $query = $db->prepare($sqlUpdateImage);

    $query->execute();
    }
    catch(PDOException $e) {
        die($e->getMessage());
    }
$myUrl = "Location: ../index.php?p=edit&pid=" . $_REQUEST['pid'];
header($myUrl);

HTML

Here is the html code where is the form with function

                    <form action="functions/upload_image.php?pid=<?php echo $productid; ?>" method="post" class="form-horizontal" enctype="multipart/form-data" data-parsley-validate>

                        <div class="form-group">
                            <label for="cimage" class="control-label col-lg-4">Nahrát obrázek</label>
                            <div class="col-lg-8">
                              <input type="file" name="pimage" id="pimage" multiple="true"/>
                            </div>
            </div>
                          <div class="form-group">
                              <center><button class="btn btn-lg btn-success" type="submit"><i class="fa fa-upload"></i> Nahrát</button></center>
                          </div>
                    </form>

Give the input an array-style name:

<input type="file" name="pimage" id="pimage[]" multiple="true"/>

Then all the entries in $_FILES['pimage'] will be arrays, and you can loop to insert them all.

$sqlImage = $db->prepare("INSERT INTO productimages (pid, pimage) VALUES (:pid, , :productimg)";
$sqlImage->bindParam(":pid", $_REQUEST['pid']);
$sqlImage->bindParam(":productimg", $productimg);

foreach ($_FILES['pimage']['name'] as $i => $name) {
    $tmp_name = $_FILES['pimage']['tmp_name'][$i];
    $temp = explode(".", $name);
    $extension = end($temp);
    $productimg = generateRandomString() . "." . $extension;
    move_uploaded_file($temp_name, "../../images/products/" . $productimg);

    try {
        $sqlImage->execute();
    } catch(PDOException $ecop) {
        die($ecop->getMessage());
    }

    // .. similar code for other queries
}

Note also the use of bindParam() to prevent SQL injection.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM