我可以上传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>
答案 0 :(得分:3)
您可以添加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>
或者让您的一个输入允许multiple
输入
<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
}
?>
答案 1 :(得分:0)
这个问题很好..
database.sql
CREATE TABLE IF NOT EXISTS `database_latihan` (
`id` tinyint(3) NOT NULL,
`kode` varchar(10) NOT NULL,
`tipe` varchar(50) NOT NULL,
`images1` varchar(100) DEFAULT NULL,
`images2` varchar(100) DEFAULT NULL,
`images3` varchar(100) DEFAULT NULL,
`images4` varchar(100) DEFAULT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=1 ;
ALTER TABLE `database_latihan`
ADD PRIMARY KEY (`id`);
ALTER TABLE `database_latihan`
MODIFY `id` tinyint(3) NOT NULL AUTO_INCREMENT,AUTO_INCREMENT=1;
koneksi.php
<?php
$hostname = "localhost";
$database = "database";
$port = '3306';
$username = "root";
$password = "";
try
{
/* set server */
$server = "mysql:host=$hostname;dbname=$database;port=$port";
/* set attribute */
$setAttribute = array(
PDO::MYSQL_ATTR_INIT_COMMAND => "SET NAMES 'utf8'",
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,
);
$conn = new PDO($server, $username, $password, $setAttribute);
/* set the PDO error mode to exception */
//$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
}
catch(PDOException $e)
{
echo "Connection failed: " . $e->getMessage();
}
?>
的index.php
<form id="adminform" action="upload.php" 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>
</tr>
<tr>
<td>Upload Images</td>
<td rowspan="1">
<input type="file" name="upload[]" onchange="previewFiles()" multiple />
</td>
</tr>
<tr>
<td></td>
<td>
<div id="preview"></div>
</td>
</tr>
<tr>
<td></td>
<td><input type="submit" name="Input" value="Input" /><input type="submit" name="reset" value="Reset" /></td>
</tr>
</table>
</form>
<!-- preview image -->
<script>
function previewFiles() {
var preview = document.querySelector('#preview');
var files = document.querySelector('input[type=file]').files;
function readAndPreview(file) {
/* Make sure `file.name` matches our extensions criteria */
if ( /\.(jpe?g|png|gif)$/i.test(file.name) ) {
var reader = new FileReader();
reader.addEventListener("load", function () {
var image = new Image();
image.height = 100;
image.title = file.name;
image.src = this.result;
preview.appendChild( image );
}, false);
reader.readAsDataURL(file);
}
}
if (files) {
[].forEach.call(files, readAndPreview);
}
}
</script>
<!-- preview image || -->
<hr />
<table cellpadding="5" cellspacing="0" border="1">
<tr bgcolor="#CCCCCC">
<th>No.</th>
<th>Kode</th>
<th>Tipe</th>
<th>Image 1</th>
<th>Image 2</th>
<th>Image 3</th>
<th>Image 4</th>
</tr>
<?php
require_once("koneksi.php");
$result = $conn->prepare("SELECT * FROM database_latihan ORDER BY id DESC") or die($conn->error);
$result->execute();
$rows = $result->fetchAll(); /* array of object
/* cek, apakah hasil query di atas mendapatkan hasil atau tidak (data kosong atau tidak) */
if ($result->rowCount() == 0) {
echo '<tr><td colspan="7">Tidak ada data!</td></tr>'; /* menampilkan row data kosong */
} else { /* else ini artinya jika data hasil query ada */
$no = 1; /* membuat variabel $no untuk membuat nomor urut */
foreach ($rows as $row) { /* loop foreach */ ?>
<tr>
<td><?php echo $no; ?></td> <!-- menampilkan nomor urut -->
<td><?php echo $row['kode']; ?></td> <!-- menampilkan kode dari database -->
<td><?php echo $row['tipe']; ?></td> <!-- menampilkan tipe dari database -->
<td><?php echo $row['images1']; ?></td> <!-- menampilkan image dari database -->
<td><?php echo $row['images2']; ?></td> <!-- menampilkan image dari database -->
<td><?php echo $row['images3']; ?></td> <!-- menampilkan image dari database -->
<td><?php echo $row['images4']; ?></td> <!-- menampilkan image dari database -->
</tr>
<?php $no++; /* menambah jumlah nomor urut setiap row */
}
}
$conn = null;
?>
<hr />
<a href="https://developer.mozilla.org" ><h3>mozilla.org</h3></a>
<a href="https://developer.mozilla.org/en-US/docs/Web/API/FileReader/readAsDataURL" >FileReader.readAsDataURL()</a>
<a href="https://stackoverflow.com/questions/37375013/multiple-upload-images-into-mysql-database/47366585#47366585" >Multiple Upload Images into Mysql Database</a>
<hr />
upload.php的
<?php
$file_dir = "images/";
/* Check if folder not exists, then create it */
if (!file_exists($file_dir)) {
mkdir($file_dir, 0777, true);
}
if (isset($_POST["Input"])) {
/* conversi multi array */
function diverse_array($array) {
$result = [];
foreach($array as $key1 => $value1)
foreach($value1 as $key2 => $value2)
$result[$key2][$key1] = $value2;
return $result;
}
$file_multi = diverse_array($_FILES['upload']);
for ($y = 0; $y < 4; $y++) {
$image[$y] = '';
}
/* loop multi file */
for ($x = 0; $x < count($file_multi); $x++) {
/* loop array file $_FILES */
foreach ($file_multi[$x] as $key => $value) {
$file_name = $file_multi[$x]['name'];
$file_size = $file_multi[$x]['size'];
$file_tmp = $file_multi[$x]['tmp_name'];
$file_target = $file_dir . $file_name;
$errors = array();
/* Check current file formats with file secure */
$file_secure = array('jpg', 'jpeg', 'png', 'gif', 'bmp');
$file_current = strtolower(pathinfo($file_name, PATHINFO_EXTENSION)); /* (end(explode('.', $file_name) */
if (in_array($file_current, $file_secure) === false) {
$errors[] = "Sorry, <strong>{$file_current}</strong> extension not allowed";
}
}
/* Check if Errors exist, then not upload. Or if Errors NOT exist, then try upload */
if (!empty($errors)) {
/* display error */
foreach ($errors as $keyError => $valueError) {
echo "$keyError = $valueError <br />";
}
} else {
if (move_uploaded_file($file_tmp, $file_target)) {
$image[$x] = $file_target;
echo "<strong>{$file_name}</strong> has been uploaded." . "<br />";
} else {
echo "Sorry, there was an something wrong in <b>move_uploaded</b>.";
}
}
}
/* Check for error */
if (!empty($errors)) {
/* Check errors and display them */
foreach ($errors as $keyError => $valueError) {
echo "$keyError = $valueError <br />";
}
/* if everything is ok, try to upload file */
} else {
/* Insert Form Data into Database */
$kode = $_POST['Kode'];
$tipe = $_POST['Tipe'];
$image1 = $image[0];
$image2 = $image[1];
$image3 = $image[2];
$image4 = $image[3];
require_once("koneksi.php");
$sql = "INSERT INTO database_latihan (kode,
tipe,
images1,
images2,
images3,
images4)
VALUES (:kode,
:tipe,
:image1,
:image2,
:image3,
:image4)";
$parameter = array(':kode' => $kode,
':tipe' => $tipe,
':image1' => $image1,
':image2' => $image2,
':image3' => $image3,
':image4' => $image4);
$query = $conn->prepare($sql);
$query->execute($parameter);
echo "Data succesfully inserted !!";
$conn = null;
/* Insert Form Data into Database || */
}
} else {
//header("location: index.php");
}
?>
<a href="index.php">Index</a>