I'm new here.
I need to upload Multiple mp3 files to a directory and store them in the 'audio' table in mysql.
I'm using this script but it works only with one file, it's annoying to do one track each time. That's why I need a multiple upload script.
I wish to only write the title of each track like this:
php: file1.mp3 [0] file2.mp3 [1] file3.mp3 [2]
html form: File 1 title: .... File 2 title: .... File 3 title: ....
insert to 'audio'
Sorry for my bad English. i hope you know what I mean
<?php if(isset($_POST['kkupload'])){
$filename = $_FILES['foto']['name'];
$extensie = substr($filename, -3);
$map = "/mounted-storage/home150/sub007/sc80538-VHHY//audio/files/";
$file = $_FILES['foto'];
$breedte = $_FILES['foto'];
$max_bytes = 100000000000;
if(strtolower($extensie) != "mp3" && strtolower($extensie) != "jpg" && strtolower($extensie) != "jpeg" && strtolower($extensie) != "png" && strtolower($extensie) != "bmp")
{
echo "Je kan alleen .gif, .jpg .jpeg en .png bestanden uploaden!";
}
elseif($_FILES['foto']['size'] > $max_bytes) { echo("Het bestand is groter dan ".$max_bytes." bytes!"); }
else {
$length = strlen($filename);
$name = "pict";
$name = substr($filename, 0, $length - 4);
$i = "1";
$tempname = $name;
$picName = $_FILES['foto']['name'];
$titel = htmlspecialchars($_POST['titel']);
$bericht = $_POST['bericht'];
$url = htmlspecialchars($_POST['pica']);
$youtube = $_POST['youtube'];
$nr = rand(0,99999999999);
if(file_exists($_FILES['foto']['name']))
{
$picName = $nr. $_FILES['foto']['name'];
if(file_exists($picName))
{
$picName = $nr. $_FILES['foto']['name'];
}
}
move_uploaded_file($_FILES['foto']['tmp_name'], $map.$_FILES['foto']['name']."") or die("Fout met uploaden plaatje");
mysql_query("INSERT INTO `audio` (titel, url, categorie) values ('".$titel."', '/audio/files/".$picName."','".$bericht."')");
echo "je hebt succesvol nieuws geupload!"; }}?>
<form action="?pagina=addnieuws" method="post" enctype="multipart/form-data" name="form1" id="form1">
<table width="100%" border="0" cellpadding="2" cellspacing="2" id="form1">
<tr>
<td width="77"><b> <font size="2" face="Verdana">Tite track:</font></b>
</div></td>
<td><font size="2">
<input name="titel" type="text" id="Titel" size="63" />
</font></td>
</tr>
<tr>
<td width="77"><b> <font size="2" face="Verdana">Plaatje:</font></b>
</div></td>
<td><font size="2">
<input type="file" name="foto" size="52" />
</font><b><font size="1" face="Verdana"> <br />
MP3</font></b></td>
</tr>
<tr>
<td valign="top" width="77"><b> <font size="2" face="Verdana">Artiest:</font></b>
</div></td>
<td>
<script type="text/javascript">
bkLib.onDomLoaded(function() {
new nicEditor({fullPanel : true}).panelInstance('area2');
});
</script>
<select name="bericht">
<?php
$query = mysql_query("SELECT * FROM artiesten ORDER BY naam ASC");
while ($array = mysql_fetch_assoc($query)){
echo "<option value=\"". $array['naam'] ."\">". $array['naam']. "</option>";
}
?>
</select>
</td>
</tr>
<tr>
<td width="77" colspan="2"><font size="2">
<input type="submit" name="kkupload" value="Upload" />
</font></td>
</tr>
</table>
</form>
The code below is a example to give you a idea of how to upload more then one file at a time but to a folder
for($i=0; $i < count($_FILES['filesToUpload']['name']); $i++){
$target_dir = "../uploads/";
$target_file = $target_dir . basename($_FILES['filesToUpload']['name'][$i]);
$uploadOk = 1;
Insert your security check code here between the above and below code to see if the file really is a mp3 and etc.
if ($uploadOk == 0) {
echo "Sorry, your file was not uploaded. ";
} else {
if (move_uploaded_file($_FILES["filesToUpload"]["tmp_name"][$i], $target_file)) {
echo "The file ". basename( $_FILES["filesToUpload"]["name"][$i]). " has been uploaded. ";
} else {
echo "Sorry, there was an error uploading your file. ";
}
}
}
Also, depending on the type of database you're using, probably best to save the files in a folder and not directly inside the database so that you're not over-bloating the database.. You instead would need to save its file path to the database and then open from the file path. Though that's just giving you a suggestion.
Lastly, that's just the PHP side of it, not sure what you'll need for the SQL part. Though I guess that's fine since you mainly asked for how to do multiple file uploads.
Related
I am working on small page where I update MySQL records via PHP page, all the functionality is well working but I constantly get warnings for an Undefined array.
Here are the warnings:
Warning: Undefined array key "file" in C:\xampp\htdocs\crud\edit.php on line 11
Warning: Trying to access array offset on value of type null in C:\xampp\htdocs\crud\edit.php on line 11
Warning: Undefined array key "file" in C:\xampp\htdocs\crud\edit.php on line 22
Warning: Trying to access array offset on value of type null in C:\xampp\htdocs\crud\edit.php on line 22
I was looking at many topics like this but did not manage to fix my own one...
Here is the code of edit.php
include 'db.php';
// File upload path
$targetDir = "uploads/";
$fileName = basename($_FILES["file"]["name"]);
$targetFilePath = $targetDir . $fileName;
$fileType = pathinfo($targetFilePath,PATHINFO_EXTENSION);
if(isset($_POST["submit"]) && !empty($_FILES["file"]["name"])){
}
// Allow certain file formats
$allowTypes = array('jpg','png','jpeg','gif','pdf','doc','xlsx');
if(in_array($fileType, $allowTypes)){
}
// Upload file to server
if(move_uploaded_file($_FILES["file"]["tmp_name"], $targetFilePath)){
}
I have also a pcs of HTML for that in <form:
<form name="update_user" method="post" action="edit.php" enctype="multipart/form-data" >
<tr>
<td>Нов сертификат:</td>
<td><input type="file" name="file" ></td>
</tr>
I have a feeling that I missed something very simple.
----- update -------
here is my full code: in one file I put php with the html
// include database connection file
include_once("config.php");
//тук стартирам за фаил ъплоад
// Include the database configuration file
include 'db.php';
// File upload path
$targetDir = "uploads/";
$fileName = basename($_FILES["file"]["name"]);
$targetFilePath = $targetDir . $fileName;
$fileType = pathinfo($targetFilePath,PATHINFO_EXTENSION);
if(isset($_POST["submit"]) && !empty($_FILES["file"]["name"])){
}
// Allow certain file formats
$allowTypes = array('jpg','png','jpeg','gif','pdf','doc','xlsx');
if(in_array($fileType, $allowTypes)){
}
// Upload file to server
if(move_uploaded_file($_FILES["file"]["tmp_name"], $targetFilePath)){
}
// край на фаил ъплоад
// Check if form is submitted for user update, then redirect to homepage after update
if(isset($_POST['update']))
{
$id = $_POST['id'];
$toolnr=$_POST['toolnr'];
$status=$_POST['status'];
$toolname=$_POST['toolname'];
$serial=$_POST['serial'];
$usedat=$_POST['usedat'];
$owner=$_POST['owner'];
$calibrated=$_POST['calibrated'];
$nextcalibration=$_POST['nextcalibration'];
$vendors=$_POST['vendors'];
// update user data
$result = mysqli_query($mysqli, "UPDATE tools SET toolnr='$toolnr',status='$status',toolname='$toolname',serial='$serial',usedat='$usedat',owner='$owner',calibrated='$calibrated',nextcalibration='$nextcalibration', vendors='$vendors', file_name = '$fileName' WHERE id='$id'");
// Redirect to homepage to display updated user in list
header("Location: index.php");
}
?>
<?php
// Display selected user data based on id
// Getting id from url
$id = $_GET['id'];
// Fetech user data based on id
$result = mysqli_query($mysqli, "SELECT * FROM tools WHERE id=$id");
while($user_data = mysqli_fetch_array($result))
{
$toolnr = $user_data['toolnr'];
$status = $user_data['status'];
$toolname = $user_data['toolname'];
$serial = $user_data['serial'];
$usedat = $user_data['usedat'];
$owner = $user_data['owner'];
$calibrated = $user_data['calibrated'];
$nextcalibration = $user_data['nextcalibration'];
$vendors = $user_data['vendors'];
$momenten = $user_data['file_name'];
}
?>
<html>
<head>
<title>Актуализация</title>
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap#4.6.2/dist/css/bootstrap.min.css" integrity="sha384-xOolHFLEh07PJGoPkLv1IbcEPTNtaed2xpHsD9ESMhqIYd0nLMwNLD69Npy4HI+N" crossorigin="anonymous">
<center> <img src="logo-ottobock.png" alt="OttobockLogo"> </center>
<hr> <br>
<center> <img src="notification.png" alt="Warning"> </center>
<center> <i> <p style="color:red;"> В момента работите с най-високо ниво на достъп, моля бъдете внимателни. <br> Всички направени от Вас промени са необратими. <p> </i> </center>
</head>
<body>
<br/><br/>
<center> <form name="update_user" method="post" action="edit.php" enctype="multipart/form-data" >
<table border="0" class="table table-striped" >
<tr>
<td>Номер</td>
<td><input type="text" name="toolnr" class="form-control" value=<?php echo $toolnr;?>></td>
</tr>
<tr>
<td>Статус</td>
<td>
<select name="status" id="status" class="form-control" required>
<?php
include "dbConn.php";
$records = mysqli_query($db, "SELECT status FROM tools WHERE id=$id UNION SELECT currentstatus FROM statuses");
while($data = mysqli_fetch_array($records))
{
echo "<option value='". $data['status'] ."'>" .$data['status'] ."</option>";
}
?> </select>
</td>
</tr>
<tr>
<td>Найменование</td>
<td><input type="text" name="toolname" class="form-control" value="<?php echo $toolname;?>"></td>
</tr> <br>
<tr>
<td>Сериен номер</td>
<td><input type="text" name="serial" class="form-control" value="<?php echo $serial;?>"></td>
</tr>
<tr>
<td>Локация</td>
<td>
<select name="usedat" id="usedat" class="form-control" required>
<?php
include "dbConn.php";
$records = mysqli_query($db, "SELECT usedat FROM tools WHERE id=$id UNION SELECT locations From whereused");
while($data = mysqli_fetch_array($records))
{
echo "<option value='". $data['usedat'] ."'>" .$data['usedat'] ."</option>";
}
?> </select>
</td>
</tr>
<tr>
<td>Отговорник</td>
<td>
<select name="owner" id="owner" class="form-control" required>
<?php
include "dbConn.php";
$records = mysqli_query($db, "SELECT owner FROM tools WHERE id=$id UNION SELECT responsiblepersons From responsibles");
while($data = mysqli_fetch_array($records))
{
echo "<option value='". $data['owner'] ."'>" .$data['owner'] ."</option>";
}
?> </select>
</td>
</tr>
<tr>
<td>Калибриран на:</td>
<td><input type="date" name="calibrated" class="form-control" value=<?php echo $calibrated;?>></td>
</tr>
<tr>
<td>Следваща</td>
<td><input type="date" name="nextcalibration" class="form-control" value=<?php echo $nextcalibration;?>></td>
</tr>
<tr>
<td>Сертификат</td>
<td><?php echo "<a target = '_blank' href='http://10.171.2.15/crud/uploads/$momenten'> Свали </a>";?></td>
</tr>
<tr>
<td>Нов сертификат:</td>
<td><input type="file" name="file" ></td>
</tr>
<tr>
<td>Калибрира се при</td>
<td>
<select name="vendors" id="vendors" class="form-control" required>
<?php
include "dbConn.php";
$records = mysqli_query($db, "SELECT vendors FROM tools WHERE id=$id UNION SELECT vendoren FROM vendors");
while($data = mysqli_fetch_array($records))
{
echo "<option value='". $data['vendors'] ."'>" .$data['vendors'] ."</option>";
}
?> </select>
</td>
</tr>
<tr>
<td><input type="hidden" name="id" value=<?php echo $_GET['id'];?>></td>
<td><input type="submit" name="update" class="btn btn-success" value="Запис">
<a href="index.php" class="btn btn-danger" >Отказ</a> </td>
</tr>
</table>
</form> </center>
</body>
Posting working code:
final-fixed code (only php part). The problem was that the part of the code responsible for file upload was out of the if statement
<?php
// include database connection file
include_once("config.php");
// Check if form is submitted for user update, then redirect to homepage after update
if(isset($_POST['update']))
{
$id = $_POST['id'];
$toolnr=$_POST['toolnr'];
$status=$_POST['status'];
$toolname=$_POST['toolname'];
$serial=$_POST['serial'];
$usedat=$_POST['usedat'];
$owner=$_POST['owner'];
$calibrated=$_POST['calibrated'];
$nextcalibration=$_POST['nextcalibration'];
$vendors=$_POST['vendors'];
// Include the database configuration file
include 'db.php';
$statusMsg = '';
// File upload path
$targetDir = "uploads/";
$fileName = basename($_FILES["file"]["name"]);
$targetFilePath = $targetDir . $fileName;
$fileType = pathinfo($targetFilePath,PATHINFO_EXTENSION);
if(isset($_POST["submit"]) && !empty($_FILES["file"]["name"])){
// Allow certain file formats
$allowTypes = array('jpg','png','jpeg','gif','pdf','doc','xlsx');
if(in_array($fileType, $allowTypes)){
}
}
// Upload file to server
if(move_uploaded_file($_FILES["file"]["tmp_name"], $targetFilePath)){
}
// update user data
$result = mysqli_query($mysqli, "UPDATE tools SET toolnr='$toolnr',status='$status',toolname='$toolname',serial='$serial',usedat='$usedat',owner='$owner',calibrated='$calibrated',nextcalibration='$nextcalibration', vendors='$vendors', file_name = '$fileName' WHERE id='$id'");
// Redirect to homepage to display updated user in list
header("Location: index.php");
}
?>
I have this add button to select the file inside a upload form field:
$("#add_attachment").on('click', function() {
var no_attachment = parseInt($('#noa').val()) + 1;
$('#noa').val(no_attachment);
$("#tbody_attachment").append("<tr><td bgcolor='#d9d9d9' class='td-data_1'><div class='col-xs-12'><input type='number' class='form-control' name='noa_save[]' id='noa_save' placeholder='No' value='" + no_attachment + "' /></div></td><td bgcolor='#d9d9d9' class='td-data_1'><div class='col-xs-12'><input type='file' class='form-control' name='attachment_save[]' id='attachment_save' placeholder='Attachment'/></div></td><td bgcolor='#d9d9d9' class='td-data_1'><div align='center'><input type='button' name='attachment' id='remove_attachment' value='Remove' style='font-size:16px; width: 98%;'/></div></td></tr>");
});
$("#tbody_attachment").on('click', '#remove_attachment', function() {
$(this).closest('tr').remove();
var no_attachment = $('#noa').val();
$('#noa').val(parseInt(no_attachment) - 1);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form method="post" action="save_sop.php" enctype="multipart/form-data">
<div align="center">
<table class="table" id="t_attachment">
<thead>
<tr>
<th width="10%" bgcolor="#8eb4e3" class="td-data_1">
<div align="center">
<font size="3dp"><strong>No</strong></font>
</div>
</th>
<th bgcolor="#8eb4e3" class="td-data_1">
<div align="center">
<font size="3dp"><strong>Attachment</strong></font>
</div>
</th>
<th width="10%" bgcolor="#8eb4e3" class="td-data_1">
<div align="center">
<font size="3dp"><strong>Button</strong></font>
</div>
</th>
</tr>
</thead>
<tbody id="tbody_attachment">
<tr>
<td bgcolor="#d9d9d9" class="td-data_1">
<div class="col-xs-12">
<input type="number" class="form-control" name="noa" id="noa" placeholder="No" value="0" />
</div>
</td>
<td bgcolor="#d9d9d9" class="td-data_1">
<div class="col-xs-12">
<div align="justify">
<font size="3dp"><strong>Choose file after clicking Add button</strong></font>
</div>
</div>
</td>
<td bgcolor="#d9d9d9" class="td-data_1">
<div align="center"><input type="button" name="add_attachment" id="add_attachment" value="Add" style="font-size:16px; width: 98%;" /></div>
</td>
</tr>
</tbody>
</table>
</div>
</form>
You can run the code above to give an idea how's the form works.
And in the save_sop.php file, I have to upload the files that submitted from the previous form and also get the file name to be stored to MySQL database as a JSON array value.
Here's the code so far in the save_sop.php file:
<?php
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
include 'con.php';
$total_attachment = mysqli_real_escape_string($con, $_POST['noa']);
$attachment["no"] = $_POST['noa_save'];
foreach($_FILES['attachment_save']['name'] as $filename) {
$imgFile = $filename;
$tmp_dir = $_FILES['attachment_save']['tmp_name'];
$imgSize = $_FILES['attachment_save']['size'];
$folder = 'sop/attachment/'; // upload directory
$imgExt = strtolower(pathinfo($imgFile, PATHINFO_EXTENSION)); // get image extension
// valid image extensions
$valid_extensions = array('jpeg', 'jpg', 'png', 'gif'); // valid extensions
// rename uploading image
$img = rand(1000, 1000000) . "." . $imgExt; //generate the random file name
// allow valid image file formats
if (in_array($imgExt, $valid_extensions)) {
// Check file size '50MB'
if ($imgSize < 5000000) {
//move_uploaded_file($tmp_dir, $folder . $img);
} else {
$errMSG = "Sorry, your file is too large.";
}
} else {
$errMSG = "Sorry, only JPG, JPEG, PNG & GIF files are allowed.";
}
echo "Generated File Name: " . $img . "<hr />";
$attachment['attachment'] = $img;
}
$attachment_save = json_encode($attachment, true);
echo $attachment_save;
}
?>
When the echo $attachment_save called, the result I get is below.
Generated File Name: 430609.jpg
<hr />
Generated File Name: 575033.jpg
<hr />
{"no":["1","2"],"attachment":"575033.jpg"}
Inside foreach loop, I called echo "Generated File Name:" . $img; I do get the result as expected, but in the attachment array, I only get one filename instead of two.
I need to get two file name value inside the attachment['attachment'] array. The result expected should be:
{"no":["1","2"],"attachment":["430609.jpg", "575033.jpg"]}
Can anybody help me with this? thanks in advance.
Regards.
the answer lies on
$attachment. Instead of $attachment['attachment'] = $img;
it should be
$attachment['attachment'][] = $img;
and it's working perfectly.
I have a custom wordpress php page where I have a form which update a database with the posted data fra input fields.
Now I wan't to be able to upload at file/picture in a specifik folder, and store the link to the file/picture in my database. I need help to implement that, because I do not understand how to achieve that at all even though I have tried to read a lot about it.
This is my code:
If($_POST['Submit'])
{
global $wpdb;
$medlemsnr=$_POST['medlemsnr'];
$navn=$_POST['navn'];
$baadnavn=$_POST['baadnavn'];
$art=$_POST['art'];
$vaegt=$_POST['vaegt'];
$billede=$_POST['billede'];
if($wpdb->insert(
'ct_storfanger_indberetninger',
array(
'Medlemsnr' => $medlemsnr,
'navn' => $navn,
'bådnavn' =>$baadnavn,
'art' =>$art,
'vægt' =>$vaegt,
'billede' =>$billede
)
) == false) wp_die('Der var en fejl i indsendelsen. Kontakt venligst webmaster'); else echo 'Tak for din indsendelse. Den vil fremgå af listen så snart den er godkendt af juryen!<p />';
?>
<?php
}
else // else we didn't submit the form, so display the form
{
?>
<form action="" method="post" id="form">
<table style="border:none;">
<tr>
<td style="border:none;width:25%">Medlemsnr</td>
<td style="border:none;"><input name="medlemsnr" type="text" value="" /></td>
</tr>
<tr>
<td style="border:none;">Navn</td>
<td style="border:none;"><input name="navn" type="text" value="" /></td>
</tr>
<tr>
<td style="border:none;">Bådnavn</td>
<td style="border:none;"><input name="baadnavn" type="text" value="" /></td>
</tr>
<tr>
<td style="border:none;">Art</td>
<td style="border:none;">
<?php
global $wpdb;
$retrieve_data = $wpdb->get_results( "SELECT Art FROM ct_storfanger_arter");
?>
<SELECT NAME="art"><option value=""></option>
<?php
foreach ($retrieve_data as $retrieved_data){
echo "<option value='" . $retrieved_data->Art . "'>" . $retrieved_data->Art . "</option>";
}
?>
</SELECT></td>
</tr>
<tr>
<td style="border:none;">Vægt i gram</td>
<td style="border:none;"><input name="vaegt" type="text" value="" /> gram</td>
</tr>
<tr>
<td style="border:none;">Billede</td>
<td style="border:none;"><input name="billede" type="file" value="" /></td>
</tr>
</table>
<table style="border:none;">
<tr>
<td style="border:none;"><input type="submit" name="Submit" id="formsubmit" value="Indsend" /></form></td>
</tr>
</table>
</form>
<?php
} // end else no post['submit']
?>
You can use this code as a reference, heres the HTML :
<!DOCTYPE html>
<html>
<body>
<form action="upload.php" method="post" enctype="multipart/form-data">
Select image to upload:
<input type="file" name="fileToUpload" id="fileToUpload">
<input type="submit" value="Upload Image" name="submit">
</form>
</body>
</html>
and this would go on the PHP side:
<?php
$target_dir = "uploads/";
$target_file = $target_dir . basename($_FILES["fileToUpload"]["name"]);
$uploadOk = 1;
$imageFileType = pathinfo($target_file,PATHINFO_EXTENSION);
// Check if image file is a actual image or fake image
if(isset($_POST["submit"])) {
$check = getimagesize($_FILES["fileToUpload"]["tmp_name"]);
if($check !== false) {
echo "File is an image - " . $check["mime"] . ".";
$uploadOk = 1;
} else {
echo "File is not an image.";
$uploadOk = 0;
}
}
?>
Simply try this on a separated folder until you understand the code and then you will be able to implement it into your wordpress modification
And if you are loading wp_init on that module you can also use the wordpress function wp_handle_upload :
if ( ! function_exists( 'wp_handle_upload' ) ) {
require_once( ABSPATH . 'wp-admin/includes/file.php' );
}
$uploadedfile = $_FILES['file'];
$upload_overrides = array( 'test_form' => false );
$movefile = wp_handle_upload( $uploadedfile, $upload_overrides );
if ( $movefile && ! isset( $movefile['error'] ) ) {
echo "File is valid, and was successfully uploaded.\n";
var_dump( $movefile );
} else {
/**
* Error generated by _wp_handle_upload()
* #see _wp_handle_upload() in wp-admin/includes/file.php
*/
echo $movefile['error'];
}
here's the function reference : wp_handle_upload
I want to add the ID number of the row to the uploaded file file name.
e.g. if the file name is stack.pdf before uploading, after uploading it should change to stack-ID#.pdf.
This is the PHP Codes that is use to upload
$sp=mysqli_connect("localhost","root","","ara");
if($sp->connect_errno){
echo "Error <br/>".$sp->error;
}
$path="pdf/";
if(isset($_POST['upload']))
{
$path=$path.$_FILES['file_upload']['name'];
if(move_uploaded_file($_FILES['file_upload']['tmp_name'],$path))
{
echo " ".basename($_FILES['file_upload']['name'])." has been uploaded<br/>";
echo '<img src="gallery/'.$_FILES['file_upload']['name'].'" width="48" height="48"/>';
$img=$_FILES['file_upload']['name'];
$query="insert into library (path,CreatedTime) values('$img',now())";
if($sp->query($query)){
echo "<br/>Inserted to DB also";
}else{
echo "Error <br/>".$sp->error;
}
}
else
{
echo "There is an error,please retry or ckeck path";
}
}
And this is the form
<form action="accept-file.php" method="post" enctype="multipart/form-data">
<table width="384" border="1" align="center">
<tr>
<td width="108">Select File</td>
<td width="260"><label>
<input type="file" name="file_upload">
</label></td>
</tr>
<tr>
<td><label>
<input type="submit" name="upload" value="Upload File">
</label></td>
<td> </td>
</tr>
</table>
</form>
I will really appreciate your help. Thanks.
Try this:
$uploadFileName = $_FILES['file_upload']['name'];
//get extention of upload file
$attachment_ext = explode('.', $uploadFileName);
$ext_pt = $attachment_ext[1];
//Give a new name for the file
$newName = '123'.$uploadFileName.".".$ext_pt;
$path = "YOURPATHHERE/";
$save_attchment = $path.$newName ; //setting the path
move_uploaded_file($_FILES['file_upload']['tmp_name'], $save_attchment);
Currently I have a code which is working perfectly for one image upload. But i want to upload multiple images at a time with same Image Title, Image Description for image group being uploaded as these images will be used in photo slideshow(See Images below please)
My Current Code is as follows -
PHP Code -
$bsq->connect_db();
$fileName = $_FILES["image"]["name"];
$fileNameNew = preg_replace('/\s+/', '_', $fileName);
$fileTmpLoc = $_FILES["image"]["tmp_name"];
// Path and file name
$pathAndName = "uploads_admin/".$fileNameNew;
// Run the move_uploaded_file() function here
$moveResult = move_uploaded_file($fileTmpLoc, $pathAndName);
// Evaluate the value returned from the function if needed
if($_POST['action']=="add"){
$all_columns[]="image_subject";
$all_columns[]="image_name";
$all_columns[]="clinic";
$all_columns[]="image_link";
//Get All values to insert in to table
$all_values[]=addslashes($_POST["image_subject"]);
$all_values[]=addslashes($_POST["image_name"]);
$all_values[]=addslashes($_POST["clinic"]);
$all_values[]=addslashes($pathAndName );
//=====================
$qry=$bsq->webdreaminsert("sa_galleryuploads_by_admin",$all_columns,$all_values,'');
echo mysql_error();
header("location:upload_file_for_downloading_list.php");
///////////////////////////////////////////////////
}
And HTML Form For upload Image Is As follows -
<form action="" method="post" enctype="multipart/form-data" name="addtwebinar1" id="addtwebinar1" onsubmit="javascript:return validateimage1();" >
<input type="hidden" value="add" name="action" />
<table width="90%" align="center" border="0" cellpadding="0" cellspacing="0" class="ListTable1">
<tr class="HeadBr">
<td colspan="4"><div align="center"><strong>Add Images For Photo Gallery</strong></div></td>
</tr>
<tr >
<td>Image Title*</td>
<td><input name="image_name" id="image_name" type="text" size="40" value="" /></td>
</tr>
<tr>
<td>Image Description In Short*</td>
<td><input name="image_subject" id="image_subject" type="text" size="40" value="" /></td>
</tr>
<tr >
<td>Clinic Name*</td>
<td>
<select name="clinic" id="message" >
<option value="">Select Clinic</option>
<option value="arogya">1. Arogyawardhini Ayurved Clinic</option>
<option value="smruti">2. Smruti Ayurved Clinic</option>
<option value="tarpan">3. Tarpan Ayurved Clinic</option>
<option value="vishwa">4. Vishwawardhini Ayurved Clinic</option>
</select>
</td>
</tr>
<tr >
<td>Your Image For Upload* </td>
<td><label for="image">File To Upload: </label><br>
<input type="file" size="40" name="image" id="image" /><br />
</td>
</tr>
<tr>
<td></td>
<td><button >Upload</button></td>
</tr>
</table>
</form>
Current Look of My Active Image upload Form -
And I Want Like Below (Created Graphically)
You can use a for loop.
For the form, do something like this:
for($i = 1; $i <= 4; $i++) {
echo "<input type=\"file\" size=\"40\" name=\"image{$i}\" id=\"image{$i}\" /><br />";
}
And for the processing, just put all of that in a for loop as well.
for($i = 1; $i <= 4; $i++) {
$fileName = $_FILES["image".$i]["name"];
$fileNameNew = preg_replace('/\s+/', '_', $fileName);
$fileTmpLoc = $_FILES["image".$i]["tmp_name"];
// Path and file name
$pathAndName = "uploads_admin/".$fileNameNew;
// Run the move_uploaded_file() function here
$moveResult = move_uploaded_file($fileTmpLoc, $pathAndName);
// Evaluate the value returned from the function if needed
if($_POST['action']=="add"){
$image_name = mysql_real_escape_string($_POST['image_name']);
$image_subject = mysql_real_escape_string($_POST['image_subject']);
$clinic = mysql_real_escape_string($_POST['clinic']);
$image_link = "http://".$_SERVER['HTTP_HOST'].rtrim(dirname($_SERVER['REQUEST_URI']), "\\/")."/".$pathAndName;
//=====================
mysql_query("INSERT INTO `sa_galleryuploads_by_admin` VALUES ('', '{$image_name}', '{$image_subject}', '{$clinic}', '{$image_link}' )") or die(mysql_error());
if(!mysql_error()) {
echo "success";
}
}
You can edit the number that the loop goes up to, to match the number of fields/images you want to show. Good luck!
edit: You also need to sanitize validate your inputs. At the very least, use mysql_real_escape_string().
Also, mysql_* functions are deprecated. You should switch to using either mysqli or pdo. I'd suggest mysqli to start off, because it also offers a procedural approach, whereas pdo is completely object oriented.