How do I add an image to a sql database - php

I am trying to insert a title, description and an image into an sql database, below is the form.
However, the code breaks after the form is submitted. I get redirected to the next page but none of the code in the next file gets processed.
It worked fine before I added the function to add an image and there was just text.
here is the code for the form that does not get processed correctly:
<?php
if (isset($_SESSION['username'])) {
echo "<form action='/origo/addnewtopic.php?cid=".$_GET['cid']."&scid=".$_GET['scid']."'
method='POST' enctype='multipart/form-data'>
<p>Titel: </p>
<input type='text' id='topic' name='topic' size='100' />
<p>Innehåll: </p>
<textarea id='content' name='content'></textarea><br />
<input type='file' name='image'>
<input type='submit' value='Lägg till' name='submit'/></form>"; ?>
And if anyone wonders, this is the file that it sends the info to that is trying to insert text and image to the database, but none of this gets processed.
<?php
session_start();
include ('dbconn.php');
$topic = addslashes($_POST['topic']);
$content = nl2br(addslashes($_POST['content']));
$image = ($_FILES['image']);
$cid = $_GET['cid'];
$scid = $_GET['scid'];
$insert = mysqli_query($con, "INSERT INTO topics (`category_id`, `subcategory_id`, `author`, `title`, `content`, `date_posted`)
VALUES ('".$cid."', '".$scid."', '".$_SESSION['username']."', '".$topic."', '".$content."', NOW());");
$tid = mysql_insert_id();
die($tid);
if($image) {
$insert2 = mysqli_query($con, "INSERT INTO images (`category_id`, `subcategory_id`, `topic_id`, `image`)
VALUES ('".$cid."', '".$scid."', '".$tid."', '".$image."');
}
else {
die("no image");
}
if ($insert) {
header("Location: /origo/topics.php?cid=".$cid."&scid=".$scid."");
} else {
die("error");
}
?>

try using blob datatype in the DB.
also here
$content = nl2br(addslashes($_POST['content']));
You must use $_FILES rather than $_POST. As the files like images are being stored in an array $_FILES that is later being extracted from. Also you must use file_get_contents for :
$content = nl2br(addslashes(file_get_contents($_POST['content'])));
Hope this helps a little

I have tried to insert image from database using php PDO. i have not save image directly i have store image path in my database. i am store in image path in my database.
<?php
//This is a database connection
$conn = new PDO("mysql:host=localhost; dbname=newdb;", 'root', '');
?>
<!DOCTYPE html>
<html>
<head></head>
<body>
<!-- This is a post type form it is a upload images -->
<form method="post" enctype="multipart/form-data">
<input type="file" name="img" required /><br><br>
<button type="submit" name="submit-img">Store Image</button>
</form>
</body>
<html/>
<?php
if (isset($_POST['submit-img']))
{
$type = ['image/jpg', 'image/png', 'image/jpeg']; //Image type name
$img = $_FILES['img']; //Fetch files
if (in_array($img['type'], $type)) //Check file type is image or not
{
$file_tmp_name = $_FILES['img']['tmp_name'];
$file_name = $_FILES['img']['name'];
$folder = "images/".$file_name;
echo $folder;
if (move_uploaded_file($file_tmp_name, $folder)) //Upload image in folder
{
$sql = "INSERT INTO images (img) VALUES (?)";
$insert_img = $conn->prepare($sql);
if ($insert_img->execute([$file_name])) //This is a image path store in database
{
echo "<script>alert('image upload successfully...')</script>";
}
else
{
echo "Image cannot uploaded please try again";
}
}
else
{
echo "file cannot uploaded";
}
}
else
{
echo "<br>Please upload an image";
}
}
?>

Related

The image cannot be displayed because it contains errors (php)

I would like to display an image stored in my database but I keep getting that error.
The image is stored in my database as longblob.
I upload it using this piece of code in upload.php:
<body>
<form action="upload.php" method="post" enctype="multipart/form-data">
Select image to upload:
<input type="file" name="image" />
<input type="submit" name="submit" value="UPLOAD" />
</form>
<?php
if (isset($_POST["submit"])) {
$check = getimagesize($_FILES["image"]["tmp_name"]);
if ($check !== false) {
$image = $_FILES['image']['tmp_name'];
$imgContent = addslashes(file_get_contents($image));
/*
* Insert image data into database
*/
//Insert image content into database
$insert = $pdo->query("UPDATE users SET image='".$imgContent."'"."WHERE id_user = ".$posts[0]->get_id());
if ($insert) {
echo "File uploaded successfully.";
} else {
echo "File upload failed, please try again.";
}
} else {
echo "Please select an image file to upload.";
}
}
?>
Then I try to display it in getImage.php:
<?php
$id = $_GET['id'];
$query = $pdo->prepare('SELECT * FROM users WHERE username LIKE :us');
$query->bindValue(':us', $_SESSION['login'], PDO::PARAM_STR);
$query->execute();
$user = $query->fetchAll(PDO::FETCH_CLASS, "User");
header ('Content-Type: image/png');
echo $user[0]->get_image();
?>
When I go however to /getImage.php?id=1, I have the error
The image cannot be displayed because it contains errors
What am I doing wrong?
Solved: I added ob_end_clean(); before the header and it worked.

Uploading Image in PHP page

Im currently in the process of creating a simple PHP website which can display a list of NBA teams and the respective players. One of the things I'm currently working on right now is adding the ability to upload images from the page itself instead of going to PHPMyAdmin.
Here's what the page looks like right now:
I'm trying to figure out how to add the team logo the same way I can add a new team name. As you can see in the bottom part there is an Add Team option which allows the user to add a new team and that team will be registered in the database.
I've tried to write some PHP code which enables the process of uploading images but have failed to do so.
team_list.php
<?php
error_reporting(0);
require_once('../Model/database.php');
// Get all categories
$query = 'SELECT * FROM categories
ORDER BY categoryID';
$statement = $db->prepare($query);
$statement->execute();
$teams = $statement->fetchAll();
$statement->closeCursor();
// Initialize message variable
$msg = "";
// If upload button is clicked ...
if (isset($_POST['upload'])) {
// Get image name
$image = $_FILES['image'];
// image file directory
$target = "images/".basename($image);
$sql = "INSERT INTO categories (img) VALUES ('$image')";
// execute query
mysqli_query($db, $sql);
if (move_uploaded_file($_FILES['image']['tmp_name'], $target)) {
$msg = "Image uploaded successfully";
}else{
$msg = "Failed to upload image";
}
}
$result = mysqli_query($db, "SELECT * FROM categories");
?>
<!DOCTYPE html>
<html>
<!-- the head section -->
<head>
<title>NBA</title>
<link rel="stylesheet" type="text/css" href="../css/index.css">
<link rel="shortcut icon" type="image/png" href="images/favicon.ico"/>
</head>
<!-- the body section -->
<body>
<main>
<h1 id="addCategoryh1">Teams</h1>
<table id="categoryListTable">
<tr>
<th>Name</th>
<th> </th>
</tr>
<?php foreach ($teams as $team) : ?>
<tr>
<td><?php echo $team['categoryName']; ?></td>
<td>
<form action="delete_team.php" method="post"
id="delete_product_form">
<input type="hidden" name="team_id"
value="<?php echo $team['categoryID']; ?>">
<input id="deleteCategoryList" type="submit" value="Delete">
</form>
</td>
</tr>
<?php endforeach; ?>
</table>
<br>
<?php
while ($row = mysqli_fetch_array($result)) {
echo "<div id='img_div'>";
echo "<img src='images/".$row['image']."' >";
echo "<p>".$row['image_text']."</p>";
echo "</div>";
}
?>
<h2 id="add_category_h2">Add Team</h2>
<form action="add_team.php" method="post"
id="add_category_form">
<label>Name:</label>
<input type="input" name="name">
<input id="add_category_button" type="submit" value="Add">
</form>
<form method="POST" action="team_list.php" enctype="multipart/form-data">
<input type="hidden" name="size" value="1000000">
<div>
<input type="file" name="image">
</div>
<div>
<button type="submit" name="upload">POST</button>
</div>
</form>
<br>
<p>View Team List</p>
</main>
<footer id="categoryListFooter">
<p>© <?php echo date("Y"); ?> NBA</p>
</footer>
</body>
</html>
And this is the add_team.php file, which gets the data from database
<?php
// Get the team data
$name = filter_input(INPUT_POST, 'name');
// Validate inputs
if ($name == null) {
$error = "Invalid team data. Check all fields and try again.";
include('../Error/error.php');
} else {
require_once('../Model/database.php');
// Add the product to the database
$query = 'INSERT INTO categories (categoryName)
VALUES (:team_name)';
$query = "INSERT INTO categories (image) VALUES ('$fileName', '$content')";
$statement = $db->prepare($query);
$statement->bindValue(':team_name', $name);
$statement->execute();
$statement->closeCursor();
// Display the team List page
include('team_list.php');
}
?>
This is how the standing.php page looks like
updated add_team.php
// Get the team data
$name = filter_input(INPUT_POST, 'name');
// Validate inputs
if ($name == null) {
$error = "Invalid team data. Check all fields and try again.";
include('../Error/error.php');
} else {
require_once('../Model/database.php');
// Add the product to the database
$query = 'INSERT INTO categories (categoryName)
VALUES (:team_name)';
$query = "INSERT INTO categories (image) VALUES ('$fileName', '$content')";
$statement = $db->prepare($query);
$statement->bindValue(':team_name', $name);
$statement->execute();
$statement->closeCursor();
// Display the team List page
include('team_list.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
$filename = basename( $_FILES['image']['name']);
$team_name = $_POST['team_name'];
// Write the file name to the server
if(move_uploaded_file($_FILES['image']['tmp_name'], $target)) {
//Tells you if its all ok
echo "The file ". basename( $_FILES['image']['name']). " has been uploaded, and your information has been added to the directory";
// Connects to your Database
mysql_connect("renwid", "password") or die(mysql_error()) ;
mysql_select_db("nba") or die(mysql_error()) ;
//Writes the information to the database
mysql_query("INSERT INTO categories (img, team_name)
VALUES ('$filename', '$team_name')") ;
} else {
//Gives and error if its not
echo "Sorry, there was a problem uploading your file.";
}
}
?>
You have to first upload successfully to the folder then you can add record in to your database
<?php
if(isset($_POST['submit'])) {
// 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
$filename = basename( $_FILES['image']['name']);
$team_name = $_POST['team_name'];
// Write the file name to the server
if(move_uploaded_file($_FILES['image']['tmp_name'], $target)) {
//Tells you if its all ok
echo "The file ". basename( $_FILES['image']['name']). " has been uploaded, and your information has been added to the directory";
// Connects to your Database
// mysql_connect("localhost", "root", "") or die(mysql_error()) ;
// mysql_select_db("your_db") or die(mysql_error()) ;
//Writes the information to the database
// mysql_query("INSERT INTO picture (image, team_name)
// VALUES ('$filename', '$team_name')") ;
} else {
//Gives and error if its not
echo "Sorry, there was a problem uploading your file.";
}
}
?>
Your HTML should be
<form action="" method="post" enctype="multipart/form-data">
Select image to upload:
<input type="file" name="image" id="image">
<input type="text" name="team_name" id="team_name">
<input type="submit" value="Submit" name="submit">
</form>
Refer https://github.com/aslamanver/nbaTest
You should create a uniqid when uploading the image, this way depending on how many people will upload images, if one were to upload the same image as another, it wouldn't be overwritten in the database
You can do this by using the explode and end function in PHP, also look into prepared statements when using SQL statements, this is to protect your DB against SQL injections, here's a good link:
https://www.w3schools.com/php/php_mysql_prepared_statements.asp
The $_FILES has a few attributes including $_FILES["name"]["error"] which checks for errors, ideally you would make an if statement in which you specify the error condition for the file to uploaded to your DB. Also remember that you must first specify the directory before inserting it into your DB and if the file containing the code is in another folder, you use ../ to go back a directory.
When you display the image on your site you use this:
<img src="directory/<?php echo $row["row"]; ?>">

How to store images in mysql database using php

How can i store and display the images in a MySQL database. Till now i have only written the code to get the images from the user and store them in a folder, the code that i wrote till now is:
HTML FILE
<input type="file" name="imageUpload" id="imageUpload">
PHP FILE
$target_dir = "uploads/";
$target_file = $target_dir . basename($_FILES["imageUpload"]["name"]);
$uploadOk = 1;
$imageFileType = pathinfo($target_file,PATHINFO_EXTENSION);
if (move_uploaded_file($_FILES["imageUpload"]["tmp_name"], $target_file)) {
echo "The file ". basename( $_FILES["imageUpload"]["name"]). " has been uploaded.";
} else {
echo "Sorry, there was an error uploading your file.";}
I found the answer, For those who are looking for the same thing here is how I did it.
You should not consider uploading images to the database instead you can store the name of the uploaded file in your database and then retrieve the file name and use it where ever you want to display the image.
HTML CODE
<input type="file" name="imageUpload" id="imageUpload">
PHP CODE
if(isset($_POST['submit'])) {
//Process the image that is uploaded by the user
$target_dir = "uploads/";
$target_file = $target_dir . basename($_FILES["imageUpload"]["name"]);
$uploadOk = 1;
$imageFileType = pathinfo($target_file,PATHINFO_EXTENSION);
if (move_uploaded_file($_FILES["imageUpload"]["tmp_name"], $target_file)) {
echo "The file ". basename( $_FILES["imageUpload"]["name"]). " has been uploaded.";
} else {
echo "Sorry, there was an error uploading your file.";
}
$image=basename( $_FILES["imageUpload"]["name"],".jpg"); // used to store the filename in a variable
//storind the data in your database
$query= "INSERT INTO items VALUES ('$id','$title','$description','$price','$value','$contact','$image')";
mysql_query($query);
require('heading.php');
echo "Your add has been submited, you will be redirected to your account page in 3 seconds....";
header( "Refresh:3; url=account.php", true, 303);
}
CODE TO DISPLAY THE IMAGE
while($row = mysql_fetch_row($result)) {
echo "<tr>";
echo "<td><img src='uploads/$row[6].jpg' height='150px' width='300px'></td>";
echo "</tr>\n";
}
if(isset($_POST['form1']))
{
try
{
$user=$_POST['username'];
$pass=$_POST['password'];
$email=$_POST['email'];
$roll=$_POST['roll'];
$class=$_POST['class'];
if(empty($user)) throw new Exception("Name can not empty");
if(empty($pass)) throw new Exception("Password can not empty");
if(empty($email)) throw new Exception("Email can not empty");
if(empty($roll)) throw new Exception("Roll can not empty");
if(empty($class)) throw new Exception("Class can not empty");
$statement=$db->prepare("show table status like 'tbl_std_info'");
$statement->execute();
$result=$statement->fetchAll();
foreach($result as $row)
$new_id=$row[10];
$up_file=$_FILES["image"]["name"];
$file_basename=substr($up_file, 0 , strripos($up_file, "."));
$file_ext=substr($up_file, strripos($up_file, "."));
$f1="$new_id".$file_ext;
if(($file_ext!=".png")&&($file_ext!=".jpg")&&($file_ext!=".jpeg")&&($file_ext!=".gif"))
{
throw new Exception("Only jpg, png, jpeg or gif Logo are allow to upload / Empty Logo Field");
}
move_uploaded_file($_FILES["image"]["tmp_name"],"../std_photo/".$f1);
$statement=$db->prepare("insert into tbl_std_info (username,image,password,email,roll,class) value (?,?,?,?,?,?)");
$statement->execute(array($user,$f1,$pass,$email,$roll,$class));
$success="Registration Successfully Completed";
echo $success;
}
catch(Exception $e)
{
$msg=$e->getMessage();
}
}
insert image zh
-while we insert image in database using insert query
$Image = $_FILES['Image']['name'];
if(!$Image)
{
$Image="";
}
else
{
$file_path = 'upload/';
$file_path = $file_path . basename( $_FILES['Image']['name']);
if(move_uploaded_file($_FILES['Image']['tmp_name'], $file_path))
{
}
}
<!--
//THIS PROGRAM WILL UPLOAD IMAGE AND WILL RETRIVE FROM DATABASE. UNSING BLOB
(IF YOU HAVE ANY QUERY CONTACT:rahulpatel541#gmail.com)
CREATE TABLE `images` (
`id` int(100) NOT NULL AUTO_INCREMENT,
`name` varchar(100) NOT NULL,
`image` longblob NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB ;
-->
<!-- this form is user to store images-->
<form action="index.php" method="post" enctype="multipart/form-data">
Enter the Image Name:<input type="text" name="image_name" id="" /><br />
<input name="image" id="image" accept="image/JPEG" type="file"><br /><br />
<input type="submit" value="submit" name="submit" />
</form>
<br /><br />
<!-- this form is user to display all the images-->
<form action="index.php" method="post" enctype="multipart/form-data">
Retrive all the images:
<input type="submit" value="submit" name="retrive" />
</form>
<?php
//THIS IS INDEX.PHP PAGE
//connect to database.db name is images
mysql_connect("", "", "") OR DIE (mysql_error());
mysql_select_db ("") OR DIE ("Unable to select db".mysql_error());
//to retrive send the page to another page
if(isset($_POST['retrive']))
{
header("location:search.php");
}
//to upload
if(isset($_POST['submit']))
{
if(isset($_FILES['image'])) {
$name=$_POST['image_name'];
$email=$_POST['mail'];
$fp=addslashes(file_get_contents($_FILES['image']['tmp_name'])); //will store the image to fp
}
// our sql query
$sql = "INSERT INTO images VALUES('null', '{$name}','{$fp}');";
mysql_query($sql) or die("Error in Query insert: " . mysql_error());
}
?>
<?php
//SEARCH.PHP PAGE
//connect to database.db name = images
mysql_connect("localhost", "root", "") OR DIE (mysql_error());
mysql_select_db ("image") OR DIE ("Unable to select db".mysql_error());
//display all the image present in the database
$msg="";
$sql="select * from images";
if(mysql_query($sql))
{
$res=mysql_query($sql);
while($row=mysql_fetch_array($res))
{
$id=$row['id'];
$name=$row['name'];
$image=$row['image'];
$msg.= '<img src="data:image/jpeg;base64,'.base64_encode($row['image']). ' " /> ';
}
}
else
$msg.="Query failed";
?>
<div>
<?php
echo $msg;
?>

How to insert an image?

Following is my code file...
I am not able to insert the image. Getting an error as, Undefined variable: image
<html>
<head>
<title> Upload an image </title>
</head>
<body>
<form action="image-disp.php" method="post" enctype="multipart/form-data">
File:
<input type="file" name="image" value=iamge><br>
<input type="submit" value="Upload">
</form>
<?php
mysql_connect("localhost", "root", " ") or die(mysql_error());
mysql_select_db("mysql") or die(mysql_error());
echo "connected";
if (!isset($_FILES['image'] ['tmp_name'])) {
echo "Choose an image";
} else {
echo $image = addslashes($_FILES['image'] ['tmp_name']);
echo $image_name = addslashes($_FILES['image']['name']);
echo $image_size = getimagesize($_FILES['image'] ['tmp_name']);
}
if ($image_size = FALSE) {
echo "It's not an image";
} else {
$result = "INSERT INTO testblob (image_id, image, image_size) "
. "VALUES (' ' ,'$image', '$image_size')";
}
echo "inserted";
?>
</body>
</html>
better save just the name of the image in database, and the file in some folder
$result = "INSERT INTO testblob ( image, image_size)
VALUES ('$image_name', '$image_size')";
then you retrieve it like that:
<img src="path/<?php echo $row['image_name'];?>">
First create a table.
Mysql-Query
CREATE TABLE storeimage ( image_id tinyint(3) NOT NULL AUTO_INCREMENT, image blob NOT NULL, KEY image_id (image_id) ) ENGINE=MyISAM DEFAULT CHARSET=latin1;
Code to store image in database:
<html>
<body>
<form action="image-disp.php" method="POST" enctype="multipart/form-data">
File:
<input type="file" name="image" method="POST">
<input type="submit" value="submit" name= "submit">
</form>
<?php
mysql_connect("localhost", "root", "root") or die (mysql_error());
mysql_select_db("mysql") or die (mysql_error());
if (isset($_FILES['image']['tmp_name']))
{
$image = addslashes(file_get_contents($_FILES['image']['tmp_name']));
$image_name = $_FILES['image']['name'];
}
if(isset($_POST['submit']))
{
$insert = mysql_query("INSERT INTO storeimage VALUES ('', '$image')");
echo " file inserted";
}
?>
</body>
</html>
Your error is coming from PHP, not MySQL. It's saying your variable, $image, isn't defined because it's not filled with anything.
Your code isn't going to store the actual image, but instead, the filename.
You need to remove the space.
echo $image = addslashes($_FILES['image']['tmp_name']);
Also, you don't even have it executing a query...
if ($image_size == FALSE) {
echo "It's not an image";
} else {
$result = mysql_query("INSERT INTO testblob (image_id, image, image_size) "
. "VALUES (' ' ,'$image', '$image_size')");
}
Take a look here for a basic example: http://www.w3schools.com/php/php_file_upload.asp

Notice: Undefined index: image - unable to find the error

here is my error.i dont know why it is not working.i checked all the parts but i was unable to find the error.
Notice: Undefined index: image in C:\xampp\htdocs\Final\places\Ressave.php on line 27
here is my html code that pass the name of input:
<form class="form-horizontal" action="Ressave.php" method="POST" autocomplete="on">
<div class="well">
<legend>Photos</legend>
<div class="control-group">
<label class="control-label">Upload Photo: </label>
<div class="controls">
<input name="image" type="file" />
</div>
</div>
</div>
<div class="form-actions">
<button type="submit" class="btn btn-primary">Submit</button>
<button type="button" class="btn">Cancel</button>
</div>
</form>
Ressave.php is here and can not recieve the name here,so the error occure.....
<?php
{ // Secure Connection Script
include('../Secure/dbConfig.php');
$dbSuccess = false;
$dbConnected = mysql_connect($db['hostname'],$db['username'],$db['password']);
if ($dbConnected) {
$dbSelected = mysql_select_db($db['database'],$dbConnected);
if ($dbSelected) {
$dbSuccess = true;
} else {
echo "DB Selection FAILed";
}
} else {
echo "MySQL Connection FAILed";
}
// END Secure Connection Script
}
if(! $dbConnected )
{
die('Could not connect: ' . mysql_error());
}
{ // File Properties
$file = $_FILES['image']['tmp_name']; //Error comes from here(here is the prob!)
if(!isset($file))
echo "Please Choose an Image.";
else {
$image = addslashes(file_get_contents($_FILES['image']['tmp_name']));
$image_size = getimagesize($_FILES['image']['tmp_name']);
if($image_size == FALSE)
echo "That is not an image.";
else
{
$lastid = mysql_insert_id();
echo "Image Uploaded.";
}
}
}
{ //join the post values into comma separated
$features = mysql_real_escape_string(implode(',', $_POST['features']));
$parking = mysql_real_escape_string(implode(',', $_POST['parking']));
$noise = mysql_real_escape_string(implode(',', $_POST['noise']));
$good_for = mysql_real_escape_string(implode(',', $_POST['good_for']));
$ambience = mysql_real_escape_string(implode(',', $_POST['ambience']));
$alcohol = mysql_real_escape_string(implode(',', $_POST['alcohol']));
}
$sql = "INSERT INTO prestaurant ( ResName, Rating, Food_serve, Features, Parking, noise, Good_For, Ambience, Alcohol, Addition_info, Name, Address1, Zipcode1, Address2, Zipcode2, Address3, Zipcode3, City, Mobile, phone1, phone2, phone3, phone4, Email1, Email2, Fax, Website, image)".
"VALUES ('$_POST[restaurant_name]','$_POST[star_rating]','$_POST[food_served]','$features','$parking','$noise','$good_for','$ambience','$alcohol','$_POST[description]','$_POST[name]','$_POST[address1]','$_POST[zipcode1]','$_POST[address2]','$_POST[zipcode2]','$_POST[address3]','$_POST[zipcode3]','$_POST[city]','$_POST[mobile]','$_POST[phone1]','$_POST[phone2]','$_POST[phone3]','$_POST[phone4]','$_POST[email1]','$_POST[email2]','$_POST[fax]','$_POST[url]','$image')";
mysql_select_db('place');
$retval = mysql_query( $sql );
if(! $retval )
{
die('Could not enter data: ' . mysql_error());
}
echo "Entered data successfully\n";
mysql_close($dbConnected);
?>
If a file was not uploaded the $_FILES array will be empty. Specifically, if the file image was not uploaded, $_FILES['image'] will not be set.
So
$file = $_FILES['image']['tmp_name']; //Error comes from here(here is the prob!)
should be:
if(empty($_FILES) || !isset($_FILES['image']))
update
You will also have issues because you're missing the enctype attribute on your form:
<form class="form-horizontal" action="Ressave.php" method="POST" autocomplete="on" enctype="multipart/form-data">
In order to be able to process files in your form you need to add the enctype attribute.
<form method='POST' enctype='multipart/form-data' >
Hey i guess you have forgotten one important setting in form
enctype="multipart/form-data" this option is used when used with files eg image file etc
<form name="image" method="post" enctype="multipart/form-data">
Apart from that to extract the contents of the file you can use following options
$tmp_img_path = $_FILES['image']['tmp_name'];
$img_name = $_FILES['image']['name'];
to print all the content of a file use:
print_r($_POST['image']);
this is the code i have which successfully insert the data into mysql and retrieve from the DB.
"Index.PHP"
<html>
<head>
<title>PHP & MySQL: Upload an image</title>
</head>
<body>
<form action="index.php" method="POST" enctype="multipart/form-data">
File: <input type="file" name="image" /><input type="submit" value="Upload" />
</form>
<?php
mysql_connect("localhost","root","") or die(mysql_error());
mysql_select_db("registrations") or die(mysql_error());
if(!isset($_FILES['image']))
{
echo 'Please select an image.';
}
else {
$image = addslashes(file_get_contents($_FILES['image']['tmp_name']));
echo $_FILES['image']['tmp_name'];
$image_name = addslashes($_FILES['image']['name']);
$image_size = getimagesize($_FILES['image']['tmp_name']);
if($image_size==FALSE){
echo "That's not an image.";
} else {
if(!$insert = mysql_query("INSERT INTO test_image VALUES ('','$image_name','$image')"))
{
echo "Problem uploading image.";
} else {
$lastid = mysql_insert_id();
echo "Image uploaded.<p />Your image:<p /><img src=get.php?id=$lastid>";
}
}
}
?>
</body>
</html>
this is get.PHP
<?php
mysql_connect("localhost","root","") or die(mysql_error());
mysql_select_db("registrations") or die(mysql_error());
$id = addslashes($_REQUEST['id']);
$image = mysql_query("SELECT * FROM test_image WHERE id=$id");
$image = mysql_fetch_assoc($image);
$image = $image['image'];
header("Content-type: image/jpeg");
echo $image;
?>
NOTE:- please changes your DB and table name accordingly..
Thanks,
Santanu

Categories