I have successfully created the PHP script for the user to upload files to a database and also to a folder on my localhost. Until the user refreshes the page they cannot see their uploaded image. Here is my code.
<?php
error_reporting(E_ALL & ~E_NOTICE);
//connect to database
$connection = mysql_connect("localhost", "root", "") or die("can't make connection : " . mysql_error());
$database = mysql_select_db ("uploads", $connection) or die ("Could not select database");
//save the name of image in table
$query = mysql_query("select * from tbl_img") or die(mysql_error());
//retrieve all image from database and store them in a variable
while($row = mysql_fetch_array($query))
{
$img_name = $row['img'];
$image = "<img src='site_images/$img_name' /><br />";
//store all images in one variable
$all_img = $all_img . $image;
}
?>
<html>
<body>
<h1>Your Images</h1>
<?php echo $all_img;?>
</body>
</html>
<!DOCTYPE html>
<html lang="en">
Upload your image:<br />
<input name="img_field" type="file" id="img_field" /><br /><br />
<input type="submit" name="submit" id="submit" value="Submit" />
<?php
//get the posted image when the submit button is clicked
if(isset($_POST['submit']))
{
$file = $_FILES['img_field'];
$file_name = $_FILES['img_field']['name'];
$file_tmp_name = $_FILES['img_field']['tmp_name'];
//save the image in img table
//connect to database
$con = mysql_connect("localhost", "root", "") or die("can't make connection : " . mysql_error());
$db = mysql_select_db ("uploads", $con) or die ("Could not select database");
//save the name of image in table
$query = mysql_query("INSERT INTO tbl_img(img) VALUES('$file_name')") or die(mysql_error());
//upload images to this folder (complete path)
$path = "site_images/$file_name";
//use move_uploaded_file function to upload or move file to the given folder or path
if(move_uploaded_file($file_tmp_name, $path))
{
echo "File Successfully uploaded";
}
else
{
echo "Please select a file";
}
}
?>
Any help would be much appreciated, thanx :)
Related
I've got the following markup and PHP. It's for a gallery - to upload and display images. I followed through this tutorial, but for some reason the mysqli_connect_db can't find the DB. what am I missing?
<?php
include('upload.php');
?>
<form action="index.php" method="POST" enctype="multipart/form-data">
Choose File: <input type="file" name="file">
Title: <input type="text" name="nam">
<input type="submit" name="submit">
</form>
and the PHP:
<?php
$con = mysqli_connect("localhost","Melvin","") or die ("could not connect to DB");
mysqli_select_db($con, "galerie") or die ("no database");
if(isset($_POST['submit'])){
$name = $_FILES['file']['name'];
$tmp_name = $_FILES['file']['tmp_name'];
$location = 'uploads/';
$target = 'uploads/' .$name;
if(move_uploaded_file($tmp_name,$location.$name)){
echo "file uploaded";
$nam = $_POST['nam'];
$query = mysqli_query($con , "INSERT INTO images(img_name,img_title)VALUES('".$target."','$nam')");
} else {
echo "file not uploaded";
}
}
$result = mysqli_query($con, "SELECT FROM images");
while($row = mysqli_fetch_array($result)){
echo "<img src=".$row['img_name']." class='addClass'>";
}
?>
Also, this is missing what you are selecting
$result = mysqli_query($con, "SELECT FROM images");
Should be (add *):
$result = mysqli_query($con, "SELECT * FROM images");
Creating a new user with all the rights in mySQL specifically for this database solved the problem for me.
I am trying to display an image from my php page by saving the image in the database [MySql] and when I retrieve it it did't show me the image.
However, I can see the image when I click on it in MySql, but it is not shown in the php file.
Images Table:
id INT
image BLOB
index.php
<html>
<head>
<title>Uploade an image</title>
</head>
<body>
<form action="test_image.php" method="POST" enctype="multipart/form-data">
File:
<input type="file" name="image"> <input type="submit" value="Uploade">
</form>
<?php
mysql_connect("", "", "")
or die("<p>Error connecting to database: " . mysql_error() . "</p>");
mysql_select_db("test")
or die("<p>Error selecting the database: " . mysql_error() . "</p>");
// file propoerties
$file = $_FILES['image']['tmp_name'];
if(!isset($file))
echo "Please select 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's not an image";
else
{
if(!$insert = mysql_query("INSERT INTO Images (image) VALUES ('$image')"))
echo "Problem uploading image.";
else
{
$lastid = mysql_insert_id();
echo "Image uploaded <p /> Your image: <p /> <img width='500' height='500' src=getimage.php?id=$lastid>";
}
}
}
?>
</body>
</html>
getimage.php
<?php
mysql_connect("", "", "")
or die("<p>Error connecting to database: " . mysql_error() . "</p>");
mysql_select_db("test")
or die("<p>Error selecting the database: " . mysql_error() . "</p>");
$id = addslashes($_REQUEST['id']);
$image = mysql_query("SELECT * FROM Images WHERE id = $id");
$image = mysql_fetch_assoc($image);
$image = $image['image'];
header("Content-type: image/jpeg");
echo $image;
?>
I can upload the image but I can't retrieve it!!
Thank you,
you need to use img html element to view the image
for example
src here is where you are saving your image file
<img src="images/yoursavedimagenameindatabase" width="" height="">
Then you can view your saved images in view
$path="images/.$image['image']."
echo '<img width="100" height="66" src="'.$path.'" />';
This is my code for uploading video on database or move to folder.
In this code video uploaded but not insert file into database....??
please help me how to insert video in database using PHP + MySQL ?
<html>
<head>
</head>
<body>
<form ACTION="test.php" method="post" enctype="multipart/form-data">
<label for="file">Filename:</label><br>
<input type="file" name="video"><br>
<input type="submit" name="submit" value="Submit">
</form>
</body>
</html>
<?php
if(isset($_FILES['video']))
{
$name = $_FILES['video']['name'];
$type = explode('.',$name);
$type = end($type);
$size= $_FILES['video']['size'];
$random_name = rand();
$tmp= $_FILES['video']['tmp_name'];
if($type !='mp4' && $type !='MP4' && $type !='flv')
{
$message ="Video Format Not Supported";
}
else
{
move_uploaded_file($tmp, 'videos/'.$random_name.'.'.$type);
mysql_query("INSERT INTO 'videos' VALUES ('', '$name',
'videos/$random_name.$type')");
$message ="Successfully Uploaded";
}
echo "$message <br/> <br/>";
}
?>
I copied this code from my file, hope this solves your problem.
$vdo=$_FILES['uf']['name']; $target_path = "video/";
$target_path = $target_path . basename( $_FILES['uf']['name']);
$target_path . basename( $_FILES['uf']['name']);
if(move_uploaded_file($_FILES['uf']['tmp_name'], $target_path))
{ $host="mysqlbhost.com";
$username="me";
$password="me";
$db_name="db";
$tbl_name="video";
mysql_connect("$host", "$username", "$password")or die("cannot connect");
mysql_select_db ("$db_name")or die("cannot select DB");
$sql="INSERT INTO $tbl_name(video)
VALUES('$vdo')";
$result=mysql_query($sql);
echo "<div id='rslt'>"; echo "Thanks! video has been sent to ";
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;
?>
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