I am trying to create a script that has a basic file upload button and a form function. I am also trying to make a script that would be a file manager with all the input data from the form.
Form Layout:
Browse (Button) ----> When clicked prompts the user to upload only pdf files.
File Name (Form): ----> The user must put a file name
Brief Description (Form): ----> The user must put a brief description of their file
Upload (Button): ----> Once this button is hit the file is uploaded to my web server to a folder called 'files'.
File Browser Layout:
The file browser would be a table that would display all the files uploaded using the previous form. Each column in the table would show the size of the file, and show the information the uploader posted in 'File Name' and 'Brief Description'
My guess is I would need some sort of SQL database that the form information would be stored. Then I would need to make a file browser that displayed the stored information. I am not sure how to go about this task. I would really appreciate your help or ideas. Thank you for your time.
I've just wrote this without checking the errors.... here goes...
1) Create the form in upload.php
<form enctype="multipart/form-data" action="uploader.php" method="POST">
<input type="hidden" name="MAX_FILE_SIZE" value="100000" />
Choose a file to upload: <input name="uploadedfile" type="file" /><br />
description <textarea name="description" cols="15" rows="15"></textarea><br>
<input type="submit" value="Upload File" />
</form>
2) create mysql table
CREATE TABLE `uploads` (
`ID` INT NOT NULL AUTO_INCREMENT PRIMARY KEY ,
`filename` TEXT NOT NULL ,
`description` TEXT NOT NULL
) ENGINE = INNODB;
3) create uploader.php and put your credentials in mysql to match the user / pass of mysql
// Where the file is going to be placed
$target_path = "uploads/";
/* Add the original filename to our target path.
Result is "uploads/filename.extension" */
$target_path = $target_path . basename( $_FILES['uploadedfile']['name']);
$target_path = "uploads/";
$target_path = $target_path . basename( $_FILES['uploadedfile']['name']);
if(move_uploaded_file($_FILES['uploadedfile']['tmp_name'], $target_path)) {
echo "The file ". basename( $_FILES['uploadedfile']['name']).
" has been uploaded";
} else{
echo "There was an error uploading the file, please try again!";
}
// Make a MySQL Connection
mysql_connect("localhost", "admin", "1admin") or die(mysql_error());
mysql_select_db("uplodas") or die(mysql_error());
// Insert a row of information into the table "example"
mysql_query("INSERT INTO uplods
(ID, filename, description) VALUES("","'.$_FILES['uploadedfile']['name'].'", "'.mysql_real_escape_string($_POST['description']).'" ) ")
or die(mysql_error());
echo "File Uploaded!";
This will allow you to have a working upload script.
a simple file manager will be
// Make a MySQL Connection
mysql_connect("localhost", "admin", "1admin") or die(mysql_error());
mysql_select_db("uplodas") or die(mysql_error());
// Make a MySQL Connection
$query = "SELECT * FROM uploads";
$result = mysql_query($query) or die(mysql_error());
$row = mysql_fetch_array($result) or die(mysql_error());
echo $row['filename']. " - ". $row['description'] ." - DELETE | EDIT";
?>
use UPDATE and DELETE mysql queries to create your delete and edit buttons.
Hope this help!
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!
my problem is that i have a form that was supposed to save information about a comic book into a database, the information it is saving is title, description etc, also it is uploading an image of the comic to my server.
right now it does upload the image to the server, but it does not put any information into my table, and simple don't know why?
Im pretty new php and mysql so maybe it is an easy problem but i can't figure this out, and i haven't been able to find the answer online.
my table structure:
id - int(11)
title - varchar(50)
description - text
publicer - varchar(50)
image - varchar(30)
price - int(10)
status - tinyint(1)
my form is on my index.php and looks like this:
<form method="post" action="newcomic.php" enctype="multipart/form-data">
<p>Comic name:
<br><input type="text" name="title"/></p>
<p>Description of the comic:
<br><textarea name="description"></textarea></p>
<p>Publicer:
<br><input type="text" name="publicer" /></p>
<p>Image:
<br><input type="file" name="image" /></p>
<p>Price:
<br><input type="text" name="price" /></p>
<p><input type="submit" name="add" title="Add new comic to database" value="Add Comic"/></p>
</form>
And my my newcomic.php file is looking like this
<?php
//This is the directory where images will be saved
$target = "images/";
$target = $target . basename( $_FILES['image']['name']);
//This gets all the other information from the form
$title = $_POST['title'];
$description = $_POST['description'];
$publicer = $_POST['publicer'];
$image = ($_FILES['image']['name']);
$price = $_POST['price'];
// Connects to your Database
mysql_connect("localhost", "root", "root") or die(mysql_error()) ;
mysql_select_db("comic_express") or die(mysql_error()) ;
//Writes the information to the database
mysql_query("INSERT INTO products (id, title, description, publicer, image, price, status)
VALUES ('', '$title', '$description', '$publicer', '$image', '$price', '1')") ;
//Writes the photo to the server
if(move_uploaded_file($_FILES['image']['tmp_name'], $target)) {
//Tells you if its all ok
echo "The file ". basename( $_FILES['uploadedfile']['name']). " has been uploaded, and your information has been added to the directory";
}
else {
//Gives and error if its not
echo "Sorry, there was a problem uploading your file.";
}
?>
Hope that anyone can help me :)
Wrong sql syntax. You are trying to put empty string in id.
You should add some error handling to your query execution to help find what's happening.
Basic mysql error handing in php would be something like:
<?php
$link = mysql_connet(CREDS HERE);
$query = "YOUR QUERY HERE";
$result = mysql_query($query, $link);
if(!$result)
echo mysql_error();
else
//Query was successful, do whatever here
?>
You always want to make sure you that the query was successful, even if you're confident that it will.
I believe Guarana is right on this one as well, just take the id out (if you set up the table properly the id will be auto generated) or you will need actually insert the id instead of empty string.
hope this helps!
you must use mysql_error() function along with your query. so that you can found the eject problem in your sql query string.
use given edited code and try.
<?php
//This is the directory where images will be saved
$target = "images/";
$target = $target . basename( $_FILES['image']['name']);
//This gets all the other information from the form
$title = $_POST['title'];
$description = $_POST['description'];
$publicer = $_POST['publicer'];
$image = ($_FILES['image']['name']);
$price = $_POST['price'];
// Connects to your Database
mysql_connect("localhost", "root", "root") or die(mysql_error()) ;
mysql_select_db("comic_express") or die(mysql_error()) ;
//Writes the information to the database
mysql_query("INSERT INTO products (title, description, publicer, image, price, status)
VALUES ('$title', '$description', '$publicer', '$image', '$price', '1')") or die(mysql_error()) ;
//Writes the photo to the server
if(move_uploaded_file($_FILES['image']['tmp_name'], $target)) {
//Tells you if its all ok
echo "The file ". basename( $_FILES['uploadedfile']['name']). " has been uploaded, and your information has been added to the directory";
}
else {
//Gives and error if its not
echo "Sorry, there was a problem uploading your file.";
}
?>
oh yes you are inserting blank value in integer type field. check that it is primary key with auto increment. if yes leave this column means you have no need to insert it.
I'd like to include in my MySQL table a path to an image. The image path gets into the table by inserting the value of a "file" textfield (one of those Browse kind of deals). So the value that gets entered is something like: image001.jpg. But I can't seem to use that value to put an image into a html page. if it goes into the table fine, why can't I get it out?
I upload an image but I don't know where it's gone. Because there's no value entered in image field when I checked it through PhpMyadmin.
Table schema
CREATE TABLE employee_details
(
emp_image varchar(255),
employee_name varchar(50),
employee_address varchar(50),
employee_designation varchar(50),
employee_salary int(),
);
Query
$sql="
INSERT INTO employee_detail(
emp_image,
employee_name,
employee_address,
employee_contact,
employee_designation,
employee_salary
)
VALUES(
'$_POST[emp_image]',
'$_POST[employee_name]',
'$_POST[employee_address]',
'$_POST[employee_contact]',
'$_POST[employee_designation]',
'$_POST[employee_salary]'
)";
On your comment you ask how to upload and store the data to mysql. So here it is:
To get the file, you should have a script in your html like this:
<html>
<body>
<form action="upload_file.php" method="post" enctype="multipart/form-data">
<label for="file">Filename:</label>
<input type="file" name="file" id="file"><br>
<input type="submit" name="submit" value="Submit">
</form>
</body>
</html>
Now, on POST, your PHP file should look like this but please take note that you have to check if the file exists on your POST:
if ($_FILES["file"]["error"] > 0)
{
echo "Error: " . $_FILES["file"]["error"] . "<br>";
}
else
{
echo "Upload: " . $_FILES["file"]["name"] . "<br>";
echo "Type: " . $_FILES["file"]["type"] . "<br>";
echo "Size: " . ($_FILES["file"]["size"] / 1024) . " kB<br>";
echo "Stored in: " . $_FILES["file"]["tmp_name"];
}
Since the "Stored in:" part is just the temporary path, you should move to your 'real' image path using move_uploaded_file().
Let say the real/default path for your images is in:
$image_dir= '/images/';
You just have to move the file using this:
move_uploaded_file($_FILES['uploaded_file']['tmp_name'], $image_dir. $_FILES['uploaded_file']['name']);
And your full path to the image would be
$image = $final_save_dir . $_FILES['uploaded_file']['name'];
There are several ways to store the path to your database:
1st: Is to store just the filename and concatenate the path of the image in PHP using $_SERVER['DOCUMENT_ROOT'] and your default image path like:
$sql="insert into employee_detail( emp_image, employee_name, employee_address,
employee_contact, employee_designation, employee_salary)
values( '$image', '$_POST[employee_name]', '$_POST[employee_address]', '$_POST[employee_contact]',
'$_POST[employee_designation]','$_POST[employee_salary]')";
2nd: Is to store the full path like:
$sql="insert into employee_detail( emp_image, employee_name, employee_address,
employee_contact, employee_designation, employee_salary)
values( '".$_SERVER['DOCUMENT_ROOT']."\\images\\".$image."', '$_POST[employee_name]', '$_POST[employee_address]', '$_POST[employee_contact]',
'$_POST[employee_designation]','$_POST[employee_salary]')";
What I recommend is this approach wherein you will input the partial path (without the root dir) so that later you don't have a problem on deploying it:
$sql="insert into employee_detail( emp_image, employee_name, employee_address,
employee_contact, employee_designation, employee_salary)
values( 'images\\".$image."', '$_POST[employee_name]', '$_POST[employee_address]', '$_POST[employee_contact]',
'$_POST[employee_designation]','$_POST[employee_salary]')";
And make sure that the images are successfully upload to that default image dir/path.
UPDATE
I also recommend that you use mysqli_* or PDO and use prepare() method /function to prevent sql injection.
If you upload an image, it is saved in the temporary path at first. You'll have to move it to your final directory, otherwise it'll be gone after script execution. What basically happens is this:
If you have a form with some form fields (text, checkbox, textarea, whatever), AND a file field (<input type="file" name="uploaded_file" />), all 'normal' fields will be accessible with the $_POST array. The file(s) however will be accessible in the $_FILES array (see also the man page about file uploads).
Now when you receive the POST request, the uploaded files are stored in your temporary directory. If you don't do anything, it'll be deleted again after script execution. So you'd need to call the move_uploaded_file() function. Example:
$final_save_dir = '/path/to/images/dir/';
move_uploaded_file($_FILES['uploaded_file']['tmp_name'], $final_save_dir . $_FILES['uploaded_file']['name']);
And your full path to the image would be
$image_full_path = $final_save_dir . $_FILES['uploaded_file']['name'];
This path can be saved in your database:
$sql="
INSERT INTO employee_detail(
emp_image,
...
)
VALUES(
'$image_full_path',
...
)";
IMPORTANT: please take note on #brewal's comment. Your script is VERY unsafe like this.
I created a login page that when user login redirect to a pictures.php,
pictures page should contains the images of the user , I already create upload page to upload image to file directory and when the user upload an image the image link is added to a new row in the database, I need to add the image link to an exist row of the user,I already created a session for user when logged in.
So I need to add the image link to an exist row of the user.
This is the code that insert the image to a file directory and save its link to a new row of the database.
<?php
$name = $_FILES["myfile"] ["name"];
$type = $_FILES["myfile"] ["type"];
$size = $_FILES["myfile"] ["size"];
$temp = $_FILES["myfile"] ["tmp_name"];
$name = $size.$size .$name ;
$error = $_FILES["myfile"] ["error"];
if ($error > 0){
die ("Error uploading image");
}else{
mysql_query("INSERT INTO userid (imageid) VALUES ('.$name')");
move_uploaded_file($temp,"uploaded/".$name);
echo "Upload Completed";
}
?>
And the upload form is
<html>
<form action="upload.php" method="POST" enctype="multipart/form-data">
<input type="file" name="myfile">
<input type="Submit" value="Upload">
</form>
</html>
So how to the image link to an exist row of the user.
Use mysql_query("UPDATE $table_name SET imageid='{$name}' WHERE userid=$userid")
Of course substituting variables and columns with correct values
Use UPDATE query instead of INSERT. INSERT will add new row but UPDATE will update your existing data.
You have to update the row if the row where you want to add image link is already exist. So use UPDATE Query. and debug wether table is updated or not.
check in table or use or die(); after the query
I have a form wherein users can upload images and these images are being saved on a particular folder in the server. At the same time the filename of the photo is being stored in a particular field in a MySQL table.
I tried changing the filename by adding a timestamp (and it works) however this new filename is not the filename being stored on the MySQL field meaning it stores the original photo filename from the user.
Is there a way that the new filename will be the one stored on MySQL table.
Below is the code I am using:
enter code here
//This is the directory where images will be saved
$target = "pics/";
$target = $target. basename( $_FILES['photo']['name']);
//This gets all the other information from the form
$name=$_POST['name'];
$email=$_POST['email'];
$phone=$_POST['phone'];
$pic=($_FILES['photo']['name']);
// Connects to your Database
mysql_connect("localhost", "username", "password") or die(mysql_error()) ;
mysql_select_db("test") or die(mysql_error()) ;
//Writes the information to the database
mysql_query("INSERT INTO `employees` VALUES ('$name', '$email', '$phone', '$pic')") ;
//Writes the photo to the server
if(move_uploaded_file($_FILES['photo']['tmp_name'], $target))
{
//Tells you if its all ok
echo "The file ". basename( $_FILES['uploadedfile']['name']). " has been uploaded, and your information has been added to the directory";
}
else {
//Gives and error if its not
echo "Sorry, there was a problem uploading your file.";
}
?>
I want the file to be renamed into something unique and I want that unique filename be stored on the photo field of my SQL table.
Before inserting, save the new filename into a variable, then change the name, and insert the new name into the database finally.
Or, If you want to change the name after you've done the insert, run an UPDATE query on the table, where you update the filename:
UPDATE table SET filename = 'new_filename' WHERE filename = 'old_filename"
Heres some code I just wrote which does a count on how many files are currently in the system and increments it by one thus making it a unique file_name, if every file is for example "user_1.jpg" and so on.
// Connects to your Database
mysql_connect("localhost", "username", "password") or die(mysql_error()) ;
mysql_select_db("database") or die(mysql_error()) ;
//handle the form information
$name=$_POST['name'];
$email=$_POST['email'];
$phone=$_POST['phone'];
//handle our file
$photo = $_FILES['photo']['tmp_name'];
//set where the file is ment to go
$target = "pics/";
//get the base name of the file
$filename = basename($photo);
//get the extension of the requested file
$extension = substr($filename, strrpos($filename, '.') + 1);
//count the length of items in the string
$stringLength = strlen(basename($photo));
//Get the file path of the photo minus the name of the photo
$filePath = substr($photo, 0, - $stringLength);
//set the inital name of the file
$PhotoName = "username.jpg";
//set the full path and name of the file to be uploaded
$checkThisFile = $target . $PhotoName;
//count how many files are in the folder and increment it by 1 in the while loop
$filecount = count(glob($target. "*.jpg"));
//while the file can be found in the system
while(file_exists($checkThisFile)){
//increment the count till the file is unquie
$filecount++;
//change the name of the file
$PhotoName = "username_$filecount.jpg";
//set the target and name of the file to be uploaded to keep testing it through our loop
$checkThisFile = $target . $PhotoName;
//if the file is not in the system then
if(!file_exists($checkThisFile)) {
//break the while loop
break;
} //end if condition
} //end while loop
//rename the photo file from the temporary name to the full name of the file
if($renamedFile = rename("$photo", "$checkThisFile")) {
//print a success tha our file was renamed
echo "<br/>the file was renamed";
//check if our renamed file exists
if(!empty($renamedFile)) {
//print a success that our file is there
echo "<br/>The renamed file exists!";
//move the uploaded file!
if(move_uploaded_file($renamedFile, $target)) {
//print there was an error with the transfer
echo "cannot move files!";
} //end he if condition
else {
//write to the database
$MyDatabaseQuery = "INSERT INTO employees VALUES ('','$name', '$email', '$phone', '$PhotoName')";
//run the query
#mysql_query($MyDatabaseQuery);
} //end else condition
} //end if condition
} //end if condition
The point of the code is too keep running through the loop till the file is not in the system and then rename the temporary file and upload it then store only the name of the file+extension in the database with any other records you want to store. I hope this helped.
Here is the MySQL Create TABLE Script too
CREATE TABLE IF NOT EXISTS `employees` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`name` text NOT NULL,
`email` text NOT NULL,
`phone` text NOT NULL,
`picture` text NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=MyISAM DEFAULT CHARSET=latin1 AUTO_INCREMENT=1 ;
You'd have to make a system for this, since the server can't decide to make a mysql-query each time you change the name of a file.
You'd have to have some kind of admin where you present all your files in a directory, and do a command which changes both the filename and the mysql-row.