我有一个需要在其中上传一些图片的表格,但是当我在上传器中上传图片时,只会保存第一张图片。 我不知道问题出在哪里。非常感谢您的时间和帮助。
这是将图片添加到我的数据库中的php脚本
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代码,带有功能的表单在哪里
<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>
答案 0 :(得分:0)
为输入提供一个数组样式名称:
<input type="file" name="pimage" id="pimage[]" multiple="true"/>
然后$_FILES['pimage']
中的所有条目都是数组,您可以循环将其全部插入。
$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
}
还要注意使用bindParam()
来防止SQL注入。