I have a already functioning form that INSERT data into a db, i also have 4x file inputs for images, the form then adds all data, uplaods images and renames images to match the next ID and adds a random end to the filename.
this all works as intented
but i now need the filename(s) to be added to the database, sometimes the form will have 1x imaghe sometimes 4x images but im not sure how to store the filenames in the db from the below code. can anyone help? i assume the array needs to be broken down to individual filenames but not sure how to do it.
<?php
if(isset($_POST['submit'])){
// Variables for date&Time logs
$dateLog = date("y-m-d"); // DATE OF ADDITION
$timeLog = date("H:i:s", time() - 3600); // TIME OF ADDITION
// INSERT QUERY
$sql="INSERT INTO $table1 (firstname, lastname, companyname, phone, email, name, make, serial, catagory, price, location, description, sold, operational, year, clear, rip, version, service, dock, loading, available, extras, dateadded, featured)
VALUES ('$_POST[firstname]','$_POST[lastname]','$_POST[companyname]','$dateLog','No')";
$query = mysql_query($sql) or die("Cannot query the database.<br>" . mysql_error());
// start of image upload
$insert_id = mysql_insert_id() or die("Unable to get insert id for image name.<br>" . mysql_error());
extract($_POST);
$error=array();
$extension=array("jpeg","jpg","png","gif");
foreach($_FILES["files"]["tmp_name"] as $key=>$tmp_name)
{
$file_name=$_FILES["files"]["name"][$key];
$file_tmp=$_FILES["files"]["tmp_name"][$key];
$ext=pathinfo($file_name,PATHINFO_EXTENSION);
if(in_array($ext,$extension))
{
if(!file_exists("../images/listings/".$txtGalleryName."/".$file_name))
{
$filename=basename($file_name,$ext);
$newFileName=$insert_id."_".mt_rand(1, 99999).".".$ext;
move_uploaded_file($file_tmp=$_FILES["files"]["tmp_name"][$key],"../images/listings/".$txtGalleryName."/".$newFileName);
}
else
{
$filename=basename($file_name,$ext);
$newFileName=$filename.mt_rand(1, 99999).".".$ext;
move_uploaded_file($file_tmp=$_FILES["files"]["tmp_name"][$key],"../images/listings/".$txtGalleryName."/".$newFileName);
}
}
else
{
array_push($error,"$file_name, ");
}
}
// end of image upload
echo '<p>This item was added successfully</p>';
}
?>
and my form;
1: Upload : <input type="file" name="files[]"/><br />
2: Upload : <input type="file" name="files[]"/><br />
3: Upload : <input type="file" name="files[]"/><br />
4: Upload : <input type="file" name="files[]"/><br />
appreciate any help :)
you can use $rename_var = rand('111111','999999'); and prepend it before the file name like $new_changed_name = $rename_var.$_FILES['files']['name']; and then use this name while saving the file in folder like so .. move_uploaded_file('tmp_name','path/'.$new_changed_name);
and insert this $new_changed_name new name into database.
Related
I have a booking table which contain file_name and file_path, I need to upload a picture into the user row based on the noic, after I select a picture and click the upload button, it show upload success, but in the database doesn't have the picture and picture name.
$target = "upload/";
$target = $target . basename( $_FILES['file']['name']);
//This gets all the other information from the form
$file=basename( $_FILES['file']['name']);
$filename=$_POST['file_name'];
//Writes the file to the server
if(move_uploaded_file($_FILES['file']['tmp_name'], $target)) {
//Tells you if its all ok
echo "The file ". basename( $_FILES['file']['name']). " has been uploaded, and your information has been added to the directory";
// Connects to your Database
//Writes the information to the database
mysql_query("UPDATE INTO booking (file_path,file_name)
VALUES ('$file', '$filename') WHERE noic = '$_SESSION[noic]'") ;
} else {
//Gives and error if its not
echo "Sorry, there was a problem uploading your file.";
}
<form enctype="multipart/form-data" action="userstatus.php" method="POST">
<p> File Name :
<input style="background:grey;" type="text" name="file_name" value="" >
</p>
<p>
<input type="file" name="file" >
</p>
<p>
<input type="submit" name="submit" value="Upload file" style="background:grey;">
</p>
</form>
Your MySQL query is incorrect, it should be UPDATE SET... MySQL Insert statement does not support the WHERE clause so your query will fail if you directly replace UPDATE with INSERT, make the following changes,
//Writes the information to the database
mysql_query("UPDATE booking SET file_path='$file',
file_name='$filename' WHERE noic = '$_SESSION[noic]'") ;
}
NOTE: PLEASE AVOID USING php mysql* class for database queries, it has been deprecated and should not be used, Switch to PDO or MySQLi. PDO reference - http://php.net/manual/en/book.pdo.php
Have you tried to run your query
UPDATE INTO booking (file_path,file_name) VALUES ('$file', '$filename') WHERE noic = '(replace here the noic you want)'
On phpMyAdmin or MySql Workbench??
Why don't you try to run the query like this:
UPDATE booking SET file_path = '$file', SET file_name= '$filename' WHERE noic = '$_SESSION[noic]'
Also check If you have set the 775 permission to the /upload folder..
Hope I help you!
$image = file_get_contents($_FILES['image']['tmp_name']);
$image = mysql_real_escape_string($image);
mysql_query("UPDATE ngc set pic='" . $image "' WHERE username='" . $_SESSION["username"] . "'");
<form method="post" action="" enctype="multipart/form-data">
Upload Image :<input type="file" name="image" id="file">
<br><input type="submit" name="submit" value="Update!" class="btnSubmit">
</form>
i want to upload image to database..
Read this very nice example here: http://www.mysqltutorial.org/php-mysql-blob/
Also see this image gallery example here: http://www.anyexample.com/programming/php/php_mysql_example__image_gallery_(blob_storage).xml
BLOBs are data types in MySql database which can help you store image files in database directly.
Although a better way would be to store the file on the disk and store the path of that variable in the database.
get the Content of the file and save in database;
$image = addslashes(file_get_contents($_FILES['image']['tmp_name']));
Mysql:
$sql = "INSERT INTO `product_images` (`id`, `image`) VALUES ('1', '{$image}')";
First of all if you want to save the entire image into the database , you must have the pic attribute type set to BLOB , here you have two options , either save the entire image into database , or save the name after uploading the images into a specified folder with a unique name each , so you can retrieve the images by name into this directory.
I was able to develop a code in enabling users to freely upload images, while the pictures would be stored to the MySql database. But I also would like to add to the php and mysql code image categories where before uploading the image, users can select from ether category- All, People, Cities, Nature and Others then click submit. How do I add that to my php code and mysql table? See my original code below:
<?php
$dbCnn = mysql_connect('', '', '');
mysql_select_db('', $dbCnn);
if(isset($_POST) and $_SERVER['REQUEST_METHOD'] == "POST") {
$image = addslashes(file_get_contents($_FILES['file']['tmp_name']));
$insStr = "INSERT INTO imagedata(id, image) VALUES ('', '{$image}')";
mysql_query($insStr);
}
Don't store images in database because it's useless. Instead of this, store in database only path to file and file save on server.
So...
<form action="" method="post" enctype="multipart/form-data">
<input type="file" name="file">
<select name="category">
<option>Nature</opton>
<option>People</option
</select>
</form>
<?php
if(isset($_POST['category']) && isset($_FILES['file']['tmp_name'])){
//mysql connect etc
move_uploaded_file($_FILES['file']['tmp_name'], path/where/to/save/file);
mysql_query("INSERT INTO table VALUES('{$_FILES['file']['name']}', '{$_POST['category']}')");
}
I am building a forum with php and MySQL and I want to append current time to each image that users upload for their profile. I used time() function on each image file uploaded and it worked for the image file but I have trouble inserting the new filename into the database. I wanted to give each image a unique name to prevent override.
OK here is what I did: I stored the current time as $time and the filename in a variable, $photo and I tried to insert that variable’s value using $photo .= $time into the database so it has the filename as I did with each uploaded image. However the original filename is inserted into the database in every attempt.
Any workarounds?
$image = $_FILES['photo']['name'];
$time = time();
$image .= $time;
delete the existing photo
delete(image_dir/$row['current_photo.jpg']);
//does not work, but i want something like that
if(move_uploaded_file($_FILES['photo']['tmp_name'], 'image_dir/$image') {
$query = "INSERT INTO profile (user_id, profile_photo) VALUES($id, $image)";
mysqli_query($dbc, $query);
if(mysqli_affected_rows($dbc) == 1) {
echo "added to the database!";
}else {
echo "failed to add photo to the database";
}
}else {
echo "failed to upload photo";
}
how can i give the uploaded image unique the name since the original image name gets inserted in the database in every try i make?
i know the code looks funny :). just want to show the logic.
If you need a unique id, you can use the uniqid function
$name=uniqid();
you may need to use
$filename=uniqid();
Okay I know I just asked a question about this but now I have it uploading the image to the data base and tried to re do some things to get the text to go in there I added everything back in for the first name but it dosnt seem to be making its way back any help would be amazing thank you btw this community is awesome.
<html>
<head>
<title>Upload an image</title>
</head>
<body>
<form action="UploadContent.php" method="POST" enctype="multipart/form-data">
<p>FirstName:</p><input type="FirstName" name"FirstName"/>
<p>File:</p><input type="file" name="image">
<input type="submit" value="Upload">
</form>
<?php
// connect to database
include"config.php";
// file properties
$FirstName = $_POST['FirstName'];
$file = $_FILES['image']['tmp_name'];
if (!isset($file))
echo "Please select a profile pic";
else
{
$image = addslashes(file_get_contents($_FILES['image']['tmp_name']));
$image_name = addslashes($FILES['image']['name']);
$image_size = getimagesize($_FILES['image']['tmp_name']);
if ($image_size==FALSE)
echo "That isn't a image.";
else
{
$insert = mysql_query("INSERT INTO content VALUES ('".$FirstName."','','','','','','','','','$image_name','$image')");
}
}
?>
</body>
</html>
I changed my insert code as follows
$insert = mysql_query("INSERT INTO content (FirstName, LastName, Gender, City, State, BirthMonth, BirthDay, BirthYear, ProfileUrl, ProfilePicName, ProfilePic) VALUES ('".$FirstName."','".$LastName."','".$Gender."','".$City."','".$State."','".$BirthMonth."','".$BirthDay."','".$BirthYear."','".$ProfielUrl."','$image_name','$image')");
because I was trying to get this youtube video to help but still no luck
http://www.youtube.com/watch?v=xAkunfiZwYQ
Well, whether you get your answer or not but i am not agree with your approach of storing images into database, you may (not may have to) store them in a file system, and the path in database, that will be the correct way to do. here is an good stack post to read Storing images