我是PHP初学者,并建立自己的练习项目(我认为它像二手车销售在线网站) 我的问题与multiple file upload sql/php和Multiple file upload in php
非常相似以下列出了我的问题 我想在目录中上传图像并将其名称存储在数据库中。到目前为止,下面的代码工作正常(如果我上传1个文件)。我正在尝试添加3个文件输入选项,以便用户最多可以上传4个图像。
到目前为止,尝试在stackoverflow和其他在线站点中提供不同的代码,我已经能够至少上传我目录中的多个文件。但真正的问题是我不知道如何将文件的名称存储在数据库中。
(在大多数教程和建议中,我发现我应该使用1个具有多个属性的输入文件类型或者名称等于数组像文件[]并运行foreach循环。但我无法弄清楚如何继续前进并获得每个输入的文件名并将其存储在数据库中。
以下是我的参考代码。
//this is my form.addVehicle.php file to process the form
<?php
define("UPLOAD_DIR", "../uploads/");
// Check if image file is a actual image or fake image
if(isset($_POST["submit"])) {
$name = "default.jpg";
if (is_uploaded_file($_FILES["myFile"]['tmp_name'])) {
$myFile = $_FILES["myFile"];
if ($myFile["error"] !== UPLOAD_ERR_OK) {
echo "<p>An error occurred.</p>";
exit;
}
// ensure a safe filename
$name = preg_replace("/[^A-Z0-9._-]/i", "_", $myFile["name"]);
// don't overwrite an existing file
$i = 0;
$parts = pathinfo($name);
while (file_exists(UPLOAD_DIR . $name)) {
$i++;
$name = $parts["filename"] . "-" . $i . "." . $parts["extension"];
}
// preserve file from temporary directory
$success = move_uploaded_file($myFile["tmp_name"],
UPLOAD_DIR . $name);
if (!$success) {
echo "<p>Unable to save file.</p>";
exit;
}
// set proper permissions on the new file
chmod(UPLOAD_DIR . $name, 0644);
}
include_once ('../class/class.Vehicle.php');
$vehicle = new Vehicle(
$_POST['make_id'],
$_POST['yearMade'],
$_POST['mileage'],
$_POST['transmission'],
$_POST['price'],
$_POST['zone_name'],
$name,
$_POST['description']
);
}
?>
//To give a try, tested is_uploaded_file condition four different times with //different file name id like myFile1,myFile2...and path variable as $name1, //$name2...and it works as I want it to be...but I'm sure that' not the correct //way to do it..
//This is my class file with name class.Vehicle.php
include_once('class.pdoDbConnnection.php');
class Vehicle{
private $make_id;
private $yearMade;
private $mileage;
private $transmission;
private $price;
private $zone_name;
private $image_path;
private $description;
public function __construct($make_id, $yearMade, $mileage, $transmission, $price, $zone_name, $image_path, $description){
$this->make_id = $make_id;
$this->yearMade = $yearMade;
$this->mileage = $mileage;
$this->transmission= $transmission;
$this->price = $price;
$this->zone_name = $zone_name;
$this->image_path = $image_path;
$this->description = $description;
try{
$sql = "INSERT INTO cars (car_id, make_id, yearmade, mileage, transmission, price, zone_name,image_path, description) VALUES (?,?,?,?,?,?,?,?,?)";
$pdo = new DBConnection();
$stmt = $pdo->prepare($sql);
$stmt->execute(array(NULL,$this->make_id,$this->yearMade,$this->mileage,$this->transmission,$this->price,$this->zone_name,$this->image_path,$this->description));
}
catch (PDOException $e)
{
echo $e->getMessage();
}
}
}
Here are my mySql table columns (I want to insert file names in the column..while displaying it in the client side, I'm using it this way: <img alt="image" class="img-responsive" src="../uploads/<?php echo $row['image_path'] ?>">
car_id , make_id , zone_id, yearmade, mileage, transmission, price, image_path, image_path1, image_path2, image_path3, description
This is my client side form to add new cars....
..................
<form class="form-horizontal" role="form" method="post" action="../includes/form.addVehicle.php" enctype="multipart/form-data">
.....................
<div class="form-group">
<label for="description" class="col-sm-2 control-label">Upload Image</label>
<div class="col-sm-4">
<input type="file" class="form-control" id="myFile" name="myFile">
</div>
</div>
<div class="form-group">
<label for="description" class="col-sm-2 control-label">Upload Image</label>
<div class="col-sm-4">
<input type="file" class="form-control" id="myFile1" name="myFile2">
</div>
</div>
<div class="form-group">
<label for="description" class="col-sm-2 control-label">Upload Image</label>
<div class="col-sm-4">
<input type="file" class="form-control" id="myFile3" name="myFile3">
</div>
</div>
..............
答案 0 :(得分:1)
最后我最终得到了以下代码。
P.S。感谢@Andy-Brahman
的Multiple file upload in php见解<?php
if(isset($_POST['submit'])){
$uploads_dir = '../test_uploads';
foreach ($_FILES["pictures"]["error"] as $key => $error) {
if ($error == UPLOAD_ERR_OK) {
$tmp_name = $_FILES["pictures"]["tmp_name"][$key];
$name = $_FILES["pictures"]["name"][$key];
// I don't want to overwrite the existing file
$i = 0;
$parts = pathinfo($name);
while (file_exists($uploads_dir . "/" . $name)) {
$i++;
$name = $parts["filename"] . "-" . $i . "." . $parts["extension"];
}
move_uploaded_file($tmp_name, "$uploads_dir/$name");
}
}
// Test to see if I get the uploaded file name which i want to insert into database table column.
echo "<pre>";
print_r($_FILES['pictures']['name'][0]);
echo"</br></br>";
print_r($_FILES['pictures']['name'][1]);
echo"</br></br>";
print_r($_FILES['pictures']['name'][2]);
echo"</br></br>";
print_r($_FILES['pictures']['name'][3]);
echo"</br></br>";
echo "</pre>";
// test succeeds . Now I guess I can do something like $picture0 = $_FILES['pictures']['name'][0]);
// and insert $picture0,$picture1...into database..
// Am I doing everything correctly?
}
答案 1 :(得分:0)
我会举个例子,你只是为自己调整它。
<form action="file_reciever.php" enctype="multipart/form-data" method="post">
<input type="file" name="files[]" multiple/>
<input type="submit" name="submission" value="Upload"/>
</form>
PHP去(file_reciever.php
):
<?php
if (isset($_POST['submission'] && $_POST['submission'] != null) {
for ($i = 0; $i < count($_FILES['files']['name']); $i++) {
//Get the temp file path
$tmpFilePath = $_FILES['files']['tmp_name'][$i];
//Make sure we have a filepath
if ($tmpFilePath != "") {
//Setup our new file path
$newFilePath = "./uploadFiles/" . $_FILES['files']['name'][$i];
//Upload the file into the temp dir
if (move_uploaded_file($tmpFilePath, $newFilePath)) {
//Handle other code here
}
}
}
}
?>