How To Upload Multiple Images With Links To Them In mysql - php

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.

Related

Cannot read my attributes in database

<?php
header("Content-type: text/html; charset=utf-8");
require('db_connect.php');
mysql_query("SET NAMES 'utf8'");
$food_name = $_POST['food_name'];
$restaurant_name = $_POST['restaurant_name'];
$food_type = $_POST['food_type'];
$food_price = $_POST['food_price'];
$food_description = $_POST['food_description'];
$uploadfile;
$dest_folder = "picture/";
$arr = array();
$count = 0;
if(!file_exists($dest_folder)){
mkdir($dest_folder);
}
foreach($_FILES["pictures"]["error"] as $key=> $error){
if($error == UPLOAD_ERR_OK){
$tmp_name = $_FILES["pictures"]["tmp_name"][$key];
$name = $_FILES["pictures"]["name"][$key];
$uploadfile = $dest_folder.$name;
move_uploaded_file($tmp_name,$uploadfile);
$arr[$count] = $uploadfile;
$count++;
}
}
$s2 = implode(',',$arr);
$sql = "insert into foodmenu
(food_name,restaurant_name,food_type,food_price,food_description,food_img)
values
('$food_name','$restaurant_name','$food_type','$food_price','$food_description','$s2',now())";
$result = mysql_query($sql);
if($result){
echo"<script>alert('Success')</script>";
echo"<script>location.href='admin.php'</script>";
} else {
echo"<script>alert('Failure')</script>";
echo"<script>history.back();</script>";
}
?>
May I know what is the error?
Because it cannot read my $food_name till $food_description.....and foreach($_FILES["pictures"]["error"] as &key=>$error).....
Can provide any solution for it?
<form action="add_action.php" method="post" name="send" onSubmit="return Check()" enctype="multipart/form-data">
Food Name :
Food Description :
Food Price :
$
Food Type :
---
appertizers
main courses
desserts
Restaurant Name :
Images :
<input name="btnSubmit" type="submit" class="inputButton" id="btnSubmit" value=" ADD " align="middle">
</form>
<div class="listbox">
<div class="menu">
<br><br>
<form action="add_action.php" method="post" name="send" onSubmit="return Check()" enctype="multipart/form-data">
<table border="0" cellpadding="2" cellspacing="0" width="100%">
<tr>
<td width="180" align="right">Food Name :</td>
<td width="150">
<input name="food_name" type="text" class="food_namelist" style="width:300px;">
</td>
</tr>
<tr>
<td width="100" align="right">Food Description :</td>
<td width="222">
<textarea name="food_description" class="food_namelist" rows="3" style="height:100px; width:500px;"></textarea>
</td>
</tr>
<tr>
<td width="100" align="right">Food Price :</td>
<td width="222">
$
<tr>
<td width="100" align="right">Food Type :</td>
<td width="222">
<select name="food_type">
<option value="" selected>---</option>
<option value="appertizers">appertizers</option>
<option value="main courses">main courses</option>
<option value="desserts">desserts</option>
</select>
</td>
</tr>
<tr>
<td width="180" align="right">Restaurant Name :</td>
<td width="222">
<input name="restaurant_name" type="text" class="food_namelist" style="width:300px;">
</td>
</tr>
<tr>
<td align="right">Images :</td>
<td style=" ">
<input type="uploadfile" name="pictures[]" />
</td>
</tr>
</table>
<input name="btnSubmit" type="submit" class="inputButton" id="btnSubmit" value=" ADD " align="middle">
</form>
</div>
</div>
There's lot of things that may happen wrong in your form.
First one is, It is possible that your form input name and your &_POST['xyz'] names are not matching.
Second one is, Please never forget to wrap your post values in htmlspecialchars like $food_name = htmlspecialchars($_POST['food_name']);
Neither your values are thrown for injection threats.
So after two above mentioned modifications, if you still face the problem, please attach your form html.
i'm excluding your db_connect.php. Please edit the details as your own.
sql code::'
<?php
define("DB_DSN","mysql:hostname=localhost;dbname=tumy");
define("DB_USR","root");
define("DB_PASS","");
$conn = new PDO(DB_DSN,DB_USR,DB_PASS);
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_WARNING);
$food_name = htmlspecialchars($_POST['food_name']);
$restaurant_name = htmlspecialchars($_POST['restaurant_name']);
$food_type = htmlspecialchars($_POST['food_type']);
$food_price = htmlspecialchars($_POST['food_price']);
$food_description = htmlspecialchars($_POST['food_description']);
$date = now();//create a column in your database named "date(or as wish)
$dest_folder = "picture/";
$arr = array();
$count = 0;
if(!file_exists($dest_folder)){
mkdir($dest_folder);
}
foreach($_FILES["pictures"]["error"] as $key=> $error){
if($error == UPLOAD_ERR_OK){
$tmp_name = $_FILES["pictures"]["tmp_name"][$key];
$name = $_FILES["pictures"]["name"][$key];
$uploadfile = $dest_folder.$name;
move_uploaded_file($tmp_name,$uploadfile);
$arr[$count] = $uploadfile;
$count++;
}
}
$s2 = implode(',',$arr);
$sql = "INSERT INTO foodmenu
(food_name,restaurant_name,food_type,food_price,food_description,food_img,date)
VALUES
('$food_name','$restaurant_name','$food_type','$food_price','$food_description','$s2','$date')";
$st = $conn->prepare($sql);
if($st->execute()){
echo"<script>alert('Success')</script>";
echo"<script>location.href='admin.php'</script>";
} else {
echo"<script>alert('Failure')</script>";
echo"<script>history.back();</script>";
}
$conn = null;
?>`

image not uploading/moving into folder

i am uploading an image , image title is getting added to database but the file(image is not uploading/moving to the folder), i am getting 404 error for that image , i have set that folder permissions to 0777 and also max upload is 1024MB
$article_image = $_FILES['image']['name'];
$image_tmp = $_FILES['image']['tmp_name'];
define ('SITE_ROOT', realpath(dirname('_FILE_')));
move_uploaded_file($image_tmp,SITE_ROOT.'/images/$article_image');
$add="insert into articles(article_title,article_date,article_author,category,article_image,article_keywords,article_content) values ('$article_title','$article_date','$article_author','$article_category','$article_image','$article_keywords','$article_content')" ;
if(mysqli_query($conn,$add)== 1 ){
echo "<script> alert('article added')</script>";
}
else{
echo "failed".mysqli_error($conn) ;
}
}
what mistake am i doing ?
EDIT here is my html code
<form method="post" action="addarticle.php" enctype="multipart/form-data">
<table align="center">
<tr>
<td align="center"><h1> ADD ARTICLE</h1></td>
</tr>
<tr>
<td>Article Title</td>
<td><input type="text" name="title"></td>
<tr>
<td>Article Keyword</td>
<td><input type="text" name="keywords"></td>
<tr>
<td>Article Image</td>
<td><input type="file" name="image"></td>
</tr>
<td>Article Content</td>
<td><textarea name="content" cols="90" rows="30"></textarea></td>
</tr>
<tr>
<td><input type="submit" name="submit" value="submit"></td>
</tr>
</table>
</form>
Check your line with:
realpath(dirname('__FILE__'));
__FILE__
is a magic constant, and should not be wrapped in single or double quotes.
If you were to echo out the result of that function call you would probably see a different path than what you're expecting.
You're also trying to use string interpolation with single quotes around the variable instead of double:
SITE_ROOT.'/images/$article_image';
Should be:
SITE_ROOT."/images/$article_image";
Example:
if (!empty($_FILES['image'])) {
$tmp_file_to_upload = $_FILES['image'];
if ($_FILES['image']['error'] == UPLOAD_ERR_OK) {
$uploaded_name = $tmp_file_to_upload['name'];
$tmp_name = $tmp_file_to_upload['tmp_name'];
$destination = realpath(dirname(__FILE__))."images/$uploaded_name";
if (!move_uploaded_file($tmp_name, $destination)) {
die('Error uploading file.');
}
} else {
die('Error uploading file.');
}
}
Try this, Variable concatenation issue '/images/'.$article_image
move_uploaded_file($image_tmp,SITE_ROOT.'/images/'.$article_image);
instead of
move_uploaded_file($image_tmp,SITE_ROOT.'/images/$article_image');

PHP File upload script getting in the way

I have this form
If the first radio button is clicked, the textfield below it is enabled and if the 2nd radio button is clicked, the file upload is enabled and the former is disabled,vice versa. It works fine if the file upload option is chosen but if the 1st radio button is chosen and the file upload is disabled, it doesn't insert data in the database. :/ What should be done to successfully send the form details even if the file upload is disabled/empty?
CODE:
<form name="form" method="POST" enctype="multipart/form-data">
<table width="416" height="245" border="1" align="center">
<tr>
<td colspan="2">Transaction No: <input type="text" name="transaction_no" id="transaction_no" /> </td>
</tr>
<tr>
<td colspan="2" align="center">Please select the mode of payment</td>
</tr>
<tr>
<td width="183" align="center"><input name="rad" type="radio" onclick="enableField(this)" value="Smart Money" checked="checked">
Smart Money</td>
<td width="201" align="center"><input name="rad" type="radio" onclick="enableField(this)" value="BPI"> BPI Bank Deposit</td>
</tr>
<tr>
<td align="center"><input type="text" name="contactno" id="contactno"></td>
<td align="center"><input name="filename" type="file" id="filename" disabled="disabled"/></td>
</tr>
<tr>
<td>Total amount sent:</td>
<td> <input type="text" name="totalsent" id="totalsent" /></td>
</tr>
<tr>
<td>Date sent:</td>
<td> <input type="text" name="datesent" id="datesent" /></td>
</tr>
<tr>
<td colspan="2" align="center"><input name="submit" type="submit" id="submit" value="Submit" /></td>
</tr>
</table>
<input type="hidden" name="MM_insert" value="form" />
</form>
PHP
<?php
if(isset($_FILES['filename'])){
$errors = array();
$file_name = $_FILES['filename']['name'];
$file_size =$_FILES['filename']['size'];
$file_tmp =$_FILES['filename']['tmp_name'];
$file_type=$_FILES['filename']['type'];
$file_ext=strtolower(end(explode('.',$_FILES['filename']['name'])));
$expensions= array("jpeg","jpg","png");
if(in_array($file_ext,$expensions)=== false){
$errors[]="extension not allowed, please choose a JPEG or PNG file.";
}
if($file_size > 2097152){
$errors[]='File size must be excately 2 MB';
}
// pag walang error...
if (empty($errors)==true) {
// upload the file...
move_uploaded_file($file_tmp,"uploads/".$file_name);
$servername = "localhost";
$username = "root";
$password = " ";
$dbname = "admin";
// create new record in the database
include ("dbinfo.php");
mysql_query("INSERT INTO payment_form (date, Tracking, mode, ContactNo, totalsent, datesent, filename) VALUES (NOW(), '$transactionNo', '$rad', '$contactNo', '$totalSent', '$dateSent', '$file_name')") ;
header('Location: paymentform_success.php');
}else{
print_r($errors);
}
}
?>
Javascript for enable/disable
<script type="text/javascript">
function enableField(obj){
var form=obj.form;
var txtNames=['contactno','filename'], f;
var rads=document.getElementsByName(obj.name), r, i=0;
while(r=rads[i++]){
f=form[txtNames[i-1]];
if(r.checked){
f.removeAttribute('disabled');
f.focus();
}
else{
f.value='';
f.setAttribute('disabled','disabled')
}
}
}
</script>
You should first check which radio is checked and then decide what to do. It's not working because the whole script is under the if(isset($_FILES['filename'])). If the file upload is disabled then $_FILES will not be set and nothing will be executed.

Adding the row ID to the filename of the uploaded file

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);

include thumbnail upload in php sql code

I have an upload to mysql script in php that works perfectly for a property website - inserting all relevant fields and the main image.
The problem is however, this image is used in a slideshow which identifies the thumbnail as xxxxxt.png where the main image is xxxxx.png for example.
My php code is:
<?php include 'dbc.php'; page_protect();
if(!checkAdmin()) {header("Location: login.php");
exit();
}
$host = $_SERVER['HTTP_HOST'];
$host_upper = strtoupper($host);
$login_path = #ereg_replace('admin','',dirname($_SERVER['PHP_SELF']));
$path = rtrim($login_path, '/\\');
foreach($_GET as $key => $value) {
$get[$key] = filter($value);
}
foreach($_POST as $key => $value) {
$post[$key] = filter($value);
}
$uniqid = md5(uniqid(mt_rand()));
?>
<?php
if($_FILES['photo']) //check if we uploading a file
{
$target = "images/properties/";
$target = $target . basename( $_FILES['photo']['name']);
$title = mysql_real_escape_string($_POST['title']);
$desc = mysql_real_escape_string($_POST['desc']);
$extra = mysql_real_escape_string($_POST['extra']);
$postcode = mysql_real_escape_string($_POST['postcode']);
$price = mysql_real_escape_string($_POST['price']);
$pandp = mysql_real_escape_string($_POST['pandp']);
$pic = "images/properties/" .(mysql_real_escape_string($_FILES['photo']['name']));
if(move_uploaded_file($_FILES['photo']['tmp_name'], $target))
{
mysql_query("INSERT INTO `furnishings` (`title`, `postcode`, `desc`, `extra`, `productcode`, `price`, `status`, `pandp`, `photo`) VALUES ('$title', '$postcode', '$desc', '$extra', '" . $uniqid . "', '$price', 'tolet.png', '$pandp', '$pic' )") ;
echo "The property has been added to the lettings portfolio";
}
else
{
echo "Error uploading new property - please ensure all the fields are correctly entered and the file is an image";
}
}
?>
The html code for the upload form is:
<form enctype="multipart/form-data" action="addlet.php" method="POST">
<table width="600px" border="2" cellpadding="5"class="myaccount">
<tr>
<td width="135">Title: </td>
<td width="427"><input name="title" type="text" size="40"/></td>
</tr>
<tr>
<td>Description: </td>
<td><textarea name = "desc" rows="3" cols="40"></textarea></td>
</tr>
<tr>
<td>Property Features: </td>
<td><textarea name = "extra" rows="3" cols="40"></textarea></td>
</tr>
<tr>
<td>Postcode: </td>
<td><input name = "postcode" type="text" size="40" /></td>
</tr>
<tr>
<td>Price per week (£): </td>
<td><input name = "price" type="text" size="40" /></td>
</tr>
<tr>
<td>Furnished/Unfurnished: </td>
<td><input name = "pandp" type="text" size="40" /></td>
</tr>
<tr>
<td>Main Image: </td>
<td><input type="file" name="photo" class="forms" /></td>
</tr> </table></p>
<p> <input type="submit" class="CMSbutton" value="Add" /></p>
</form>
Is there a simple way to add an extra line of code which will insert two images into the desired target on the server, (images/properties/) - one the original name of the image, and one the thumbnail version (with a "t" on the end of the image name).
As they are both reasonably small I am not fussed about resizing the thumbnail as the code is pretty much done I dont want to have to rebuild everything!
Any help much appreciated
Thanks
JD
If your image file is being moved into place successfully, I would take this strategy: create columns is_uploaded, is_thumb_created and is_image_created in your database table. Upon successful upload and move, set the first one.
Then run a cron or other background system that generates a 'main' and a 'thumb' view from the uploaded image (bearing in mind that the uploaded image may be way too large for an ordinary screen-size picture). Upon the successful generation of these images, the relevant columns can be set as 'done', and the row remains non-live until this happens.
This approach is a great deal more scalable, incidentally, since it is not clogging up your web request with expensive image processing.

Categories