我可以上传 1 张图片并存储到 mysql 中,但是如何上传和存储多于 1 张图片,就像我想上传 3 张图片并存储到数据库中一样? 这是我的上传 1 张图像并存储到数据库 的代码:
在我的 sql 列名称上:kodem、tipe、images1、images2、images3
<!DOCTYPE html>
<?php
include("koneksi.php");
if(isset($_POST['Input'])) {
$Kode = $_POST['Kode'];
$Tipe = $_POST['Tipe'];
$file_name = $_FILES['images1']['name'];
$file_size = $_FILES['images1']['size'];
$file_tmp = $_FILES['images1']['tmp_name'];
$file_ext = strtolower(end(explode(".", $file_name)));
$ext_boleh = array("jpg", "jpeg", "png", "gif", "bmp");
if(in_array($file_ext, $ext_boleh)) {
$sumber = $file_tmp;
$tujuan = "images/" . $file_name;
move_uploaded_file($sumber, $tujuan);
$sql = "insert into database_latihan values ('$Kode' , '$Tipe' , '$tujuan')";
mysqli_query($koneksi, $sql);
}else {
echo "Only Images can be store!";
}
}
?>
<html>
<head>
<title>Input Database</title>
</head>
<body>
<div>
<form id="adminform" action="" method="post" enctype="multipart/form-data">
<table>
<tr>
<td>Kode </td>
<td><input type="text" name="Kode" placeholder="CAR/STH/STC" /><br /></td>
</tr>
<tr>
<td>Tipe </td>
<td><select name = "Tipe">
<option value="Cardio">Cardio</option>
<option value="Strength">Strength</option>
<option value="Stretching">Stretching</option>
</select><br /></td>
<td rowspan="1">
<input type="file" id="upload" name="images1">
</td>
</tr>
<tr>
<td><input type="submit" name="Input" value="Input" /></td>
<td><input type="submit" name="reset" value="Reset" /></td>
</tr>
</table>
</form>
</div>
</body>
</html>
最佳答案
您可以添加 3 个输入
<td rowspan="1">
<input type="file" id="upload" name="images1[]">
</td>
<td rowspan="1">
<input type="file" id="upload" name="images1[]">
</td>
<td rowspan="1">
<input type="file" id="upload" name="images1[]">
</td>
或者让你的一个输入允许多个
输入
<td rowspan="1">
<input type="file" id="upload" multiple name="images1[]">
</td>
无论哪种方式,你都会得到一个 $_FILES['images1']
现在是一个数组
然后您的 PHP 代码只需要遍历 $_FILES 数组
<?php
include("koneksi.php");
if(isset($_POST['Input'])) {
$Kode = $_POST['Kode'];
$Tipe = $_POST['Tipe'];
// you should really be checking for upload errors
foreach ($_FILES['images1']['error'] as $err) {
switch ($err) {
case UPLOAD_ERR_NO_FILE:
echo 'No file sent.';
exit;
case UPLOAD_ERR_INI_SIZE:
case UPLOAD_ERR_FORM_SIZE:
echo 'Exceeded filesize limit.';
exit;
}
}
for($x=0; $x<count($_FILES['images1']['tmp_name']); $x++ ) {
$file_name = $_FILES['images1']['name'][$x];
$file_size = $_FILES['images1']['size'][$x];
$file_tmp = $_FILES['images1']['tmp_name'][$x];
$t = explode(".", $file_name);
$t1 = end($t);
$file_ext = strtolower(end($t));
$ext_boleh = array("jpg", "jpeg", "png", "gif", "bmp");
if(in_array($file_ext, $ext_boleh)) {
$sumber = $file_tmp;
$tujuan = "images/" . $file_name;
move_uploaded_file($sumber, $tujuan);
$sql = "insert into database_latihan values ('$Kode' , '$Tipe' , '$tujuan')";
mysqli_query($koneksi, $sql);
}else {
echo "Only Images can be store!";
}
} // endfor
}
?>
关于php - 多张图片上传到Mysql数据库,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37375013/