php form does not save date into database - php

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.

Related

Fail to upload picture into existing row in the table

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 rename and value insert into my mysql

What I would like is for an uploaded image to have a random name that would would be inserted into my data base so I can call it on user profiles. I have the php code that will upload files to the local disc but no values are being submitted into the mysql row for the user. Also, all the images are being named image.jpg and overwriting each other. Any help would be great. Thanks!
<?php
//This is the directory where images will be saved
$target = "images/uploaded/user_images/";
$target = $target . basename( $_FILES['photo']['name']);
//This gets all the other information from the form
$photo=($_FILES['photo']['name']);
// Connects to your Database
mysql_connect("server", "root", "pass") or die(mysql_error()) ;
mysql_select_db("db") or die(mysql_error()) ;
//Writes the information to the database
mysql_query("INSERT INTO `users` VALUES ('$photo')") ;
//Writes the information to the database
mysql_query("INSERT INTO photo ('name')
VALUES ('$photo')") ;
//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['photo']['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.";
}
?>
For I start I would like to ask you how do you know which user has which picture? Becouse you just store images in table without any user ID. I suggest that you redesign your database.
Then I will use this for an image name instead of completely random string.
$_FILES['photo']['name'] = "image_" . round(microtime(true) * 1000) . ".jpg";
Or get the number of images in database and increase it by one. That way you cannot end up with multiple images with same name.

How to upload images into MySQL database using PHP code

I am trying to save images in my database from HTML form. I have written PHP code to accomplish this task. The program is not generating any error message, but also not inserting image data in MySQL database. Kindly check it.
Here i am sharing a excerpt from my code.
/*-------------------
IMAGE QUERY
---------------*/
$file =$_FILES['image']['tmp_name'];
if(!isset($file))
{
echo 'Please select an Image';
}
else
{
$image_check = getimagesize($_FILES['image']['tmp_name']);
if($image_check==false)
{
echo 'Not a Valid Image';
}
else
{
$image = file_get_contents ($_FILES['image']['tmp_name']);
$image_name = $_FILES['image']['name'];
if ($image_query = mysql_query ("insert into product_images values (1,'$image_name',$image )"))
{
echo $current_id;
//echo 'Successfull';
}
else
{
echo mysql_error();
}
}
}
/*-----------------
IMAGE QUERY END
---------------------*/
<form action='insert_product.php' method='POST' enctype='multipart/form-data' ></br>
File : <input type='file' name= 'image' >
</form>
Error Message
You have an error in your SQL syntax; check the manual that
corresponds to your MySQL server version for the right syntax to use
near '' at line 1
Firstly, you should check if your image column is BLOB type!
I don't know anything about your SQL table, but if I'll try to make my own as an example.
We got fields id (int), image (blob) and image_name (varchar(64)).
So the code should look like this (assume ID is always '1' and let's use this mysql_query):
$image = addslashes(file_get_contents($_FILES['image']['tmp_name'])); //SQL Injection defence!
$image_name = addslashes($_FILES['image']['name']);
$sql = "INSERT INTO `product_images` (`id`, `image`, `image_name`) VALUES ('1', '{$image}', '{$image_name}')";
if (!mysql_query($sql)) { // Error handling
echo "Something went wrong! :(";
}
You are doing it wrong in many ways. Don't use mysql functions - they are deprecated! Use PDO or MySQLi. You should also think about storing files locations on disk. Using MySQL for storing images is thought to be Bad Idea™. Handling SQL table with big data like images can be problematic.
Also your HTML form is out of standards. It should look like this:
<form action="insert_product.php" method="POST" enctype="multipart/form-data">
<label>File: </label><input type="file" name="image" />
<input type="submit" />
</form>
Sidenote:
When dealing with files and storing them as a BLOB, the data must be escaped using mysql_real_escape_string(), otherwise it will result in a syntax error.
Just few more details:
Add mysql field
`image` blob
Get data from image
$image = addslashes(file_get_contents($_FILES['image']['tmp_name']));
Insert image data into db
$sql = "INSERT INTO `product_images` (`id`, `image`) VALUES ('1', '{$image}')";
Show image to the web
<img src="data:image/png;base64,'.base64_encode($row['image']).'">
End
This is the perfect code for uploading and displaying image through MySQL database.
<html>
<body>
<form method="post" enctype="multipart/form-data">
<input type="file" name="image"/>
<input type="submit" name="submit" value="Upload"/>
</form>
<?php
if(isset($_POST['submit']))
{
if(getimagesize($_FILES['image']['tmp_name'])==FALSE)
{
echo " error ";
}
else
{
$image = $_FILES['image']['tmp_name'];
$image = addslashes(file_get_contents($image));
saveimage($image);
}
}
function saveimage($image)
{
$dbcon=mysqli_connect('localhost','root','','dbname');
$qry="insert into tablename (name) values ('$image')";
$result=mysqli_query($dbcon,$qry);
if($result)
{
echo " <br/>Image uploaded.";
header('location:urlofpage.php');
}
else
{
echo " error ";
}
}
?>
</body>
</html>

Storing the changed filename into mysql field

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.

Help with a PHP upload and file manager script

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!

Categories