My problem is that if i try to post a image trought my website to my database called photos they don't appear there. Images do appear inside the folder i created upload/img. My database photos table is called images with 2 rows. id int(11) and image MEDIUMBLOB. Any ideas why doesn't my images appear on my MYSQL database?
<?php session_start(); ?>
<!DOCTYPE html>
<html>
<head>
<title>Image Upload</title>
</head>
<body>
<?php if(isset($_SESSION['err'])){ ?>
<h2><?php echo $_SESSION['err']; ?></h2>
<?php session_unset(); } ?>
<form method="post" action="upload.php" enctype="multipart/form-data" >
<input type="file" name="image" />
<input type="submit" value="Submit" name="save">
</form>
</body>
</html>
My upload.php
<?php
require_once('config.php');
session_start();
if(isset($_POST['save']))
{
$target_dir = "upload/img/";
$filename = explode('.',$_FILES['image']['name']);
$ext = $filename[1];
$imgname = time().'.'.$ext;
$target_file = $target_dir . $imgname ;
if (move_uploaded_file($_FILES["image"]["tmp_name"], $target_file)) {
$path=$imgname;
$conn->query("INSERT INTO images (id, image)VALUES ('$path')");
$_SESSION["Success"]='Image Is Upload Success...';
header("Location:view.php"); /* Redirect browser */
exit();
} else {
$_SESSION["err"]=$text;
header("Location:index.php"); /* Redirect browser */
exit();
}
}
}
?>
Here is picture of my "images" table.
it has to be
if (move_uploaded_file($_FILES["image"]["tmp_name"], $target_file)) {
$path=$imgname;
$conn->query("INSERT INTO images (image) VALUES ('$path')");
$_SESSION["Success"]='Image Is Upload Success...';
header("Location:view.php"); /* Redirect browser */
exit();
} else {
$_SESSION["err"]=$text;
header("Location:index.php"); /* Redirect browser */
exit();
}
because you are telling Mysql to insert id but you didn't provide it's value
So i figured it out why those pictures wont upload to my MYSQL database.
Like some people here suggested i didn't need "id" written in my INSERT part.
My table id row had to be set to primary and AUTO_INCREMENT(see image below).
Now things seem to be working fine. You can set image row type from varchar to blob.
Related
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";
}
}
?>
With this code I'm trying to upload a file to mysql database and then try and display it using another code (which I don't show here). The problem I'm having is that though this script executes, the uploaded file does not show.
<!DOCTYPE html>
<html lang="en">
<body>
<div class="container" >
<form action="insert.php" method="post" class="form-horizontal" role="form" enctype="multipart/form-data">
<div class="col-sm-offset-3">
<h2>Application Results</h2>
<label for="fileSelect">Please upload your application results here:</label>
<input type="file" name="application_results" ><br>
</div>
</body>
</html>
<?php
if(isset($_POST['submit']))
{
$file = rand(1000,100000)."-".$_FILES['application_results']['name'];
$file_loc = $_FILES['file']['tmp_name'];
$folder="uploads/";
move_uploaded_file($file_loc,$folder.$file);
$sql="INSERT INTO applications(application_results) VALUES('$file')";
mysql_query($sql);
}
?>
Please give permission to that uploads folder. Also it is better to have if condition before database insert. Adding if condition there will help you to identify if file is successfully uploaded or not.
if(move_uploaded_file($file_loc,$folder.$file)) {
$sql="INSERT INTO applications(application_results) VALUES('$file')";
mysql_query($sql) or die(mysql_error());
}
If you have not solved this yet. Please try with tmp name.
move_uploaded_file($_FILES['application_results']['tmp_name'],$folder.$file)
Try this:
if(isset($_POST['submit']))
{
$uploads = $_FILES['application_results'];
$file = rand(1000,100000)."-".$_FILES['application_results']['name'];
$folder = 'uploads/' . $file;
if(move_uploaded_file($uploads['tmp_name'], $folder))
{
$sql="INSERT INTO applications(application_results) VALUES('$file')";
mysql_query($sql);
}
}
I have created a MySQL database 'tutorial_db' and in that database I have created a table with 3 columns:
I have written the following code using PHP and HTML to upload an image file and store it in the longblob 'image' column and display all the images from the database in the same page:
<?php
//connect to database
$con = mysqli_connect('localhost', 'root', '', 'tutorial_db') or die('Could not connect to database: '.mysqli_connect_error());
?>
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>Upload Image</title>
</head>
<form action="image.php" method="post" enctype="multipart/form-data">
<p><input type="file" name="image"></p>
<p><input type="submit" name="upload_image" value="Upload"></p>
</form>
<?php
error_reporting(0);
if(isset($_POST['upload_image'])) {
//check if an image file is uploaded or not.
if(getimagesize($_FILES['image']['tmp_name']) == FALSE) {
//this block is executed if a non-image file or no file is uploaded
echo 'Please upload an image!';
} else {
//this block is executed if an image is uploaded
$image = addslashes(file_get_contents($_FILES['image']['tmp_name']));
$image_name = addslashes($_FILES['image']['name']);
//query to insert images in the table
if(!mysqli_query($con, "INSERT INTO image(image_name, image) VALUES('$image_name', '$image')")) {
echo "Failed to upload image!";
}
}
//query to display all the images stored in the image database
$record = mysqli_query($con, "SELECT * FROM image");
while($rows = mysqli_fetch_assoc($record)) {
echo '<img width = "20%" height = "200px" src="data:image/jpeg;base64,'.base64_encode( $rows['image'] ).'"/>';
}
mysqli_close($con);
}
?>
<body>
</body>
</html>
It is working perfectly fine for images with resolution lower than 1920x1080. But when I try uploading images of resolution, say for example: 3840x2160 it displays the uploading failed error. I am guessing it is due to the image resolution that the error is being displayed. Is there any way to reduce the resolution of such images before storing them in the MySQL database?
I have a simple register form where the user can upload a profile picture, if the user doesn't it, it should take the default picture name called person-icon.png.
When I register an user and upload a picture it works but if i leave it blank don't do anything and that column is inserted into the DB empty
if(isset($_FILES['image'])){
$img = $_FILES['image']['name'];
}
else if(empty($_FILES['image']['name'])){
$img = 'person-icon.png';
}
I already have tried these options:
Option 1:
if (empty($_FILES['image'])){
$img = 'person-icon.png';
}
else{
$img = $_FILES['image']['name'];
}
Option 2:
if($_FILES["image"]["error"] == 4)
Option 3:
if($_FILES["image"]["name"] == "")
You could check for $_FILE['image']['name'] not equal "" this work;
See code:
<!DOCTYPE html>
<html>
<body>
<form action="upload.php" method="post" enctype="multipart/form-data">
Select image to upload:
<input type="file" name="image" id="image">
<input type="submit" value="Upload Image" name="submit">
</form>
</body>
</html>
<?php
//var_dump($_FILES);
$default_pic =" pic.png";
if (isset($_FILES['image'])){
if($_FILES['image']['name'] != ""){
echo "has pic";
}
else{
$_FILES['image']['name'] = $default_pic;
echo "has no pic";
}
}
?>
In order to check if a file has been uploaded you have to look for the tmp_name, because that is what contains the actual copy of your file content on the server.
I would do something like this:
$file = $_FILES['file']['tmp_name'];
if (!file_exists($file)){
//no image
}
else{
//image
}
You can also check $_FILES as long you don't upload other files in that form:
if(empty($_FILES)){
//no image
}
else{
//image
}
For further information check the official manual of file uploads.
I hope this helped you :)
I have a php file which stores an image in a BLOB in a Database. The uploading part works fine. However it won't display the image and I don't know why. Help appreciated.
Two files:
index.php
<!DOCTYPE HTML>
<html>
<head>
<title>Upload Image</title>
</head>
<body>
<h1>Upload an Image</h1>
<form action="index.php" method="POST" enctype="multipart/form-data">
<label for="image">File:</label>
<input type="file" name="image">
<input type="submit" value="Upload">
</form>
<?php
//connect
mysql_connect("localhost", "root","") or die(mysql_error());
mysql_select_db("up") or die(mysql_error());
//file stuff
$file= $_FILES['image']['tmp_name'];
if(!isset($file))
echo "Please select an image";
else {
$image=mysql_real_escape_string(file_get_contents($_FILES['image']['tmp_name']));
$imageName=mysql_real_escape_string($_FILES['image']['name']);
$imageSize=getimagesize($_FILES['image']['tmp_name']);
if(!$imageSize)
echo "Thats not an image";
else {
//upload
$query="INSERT INTO store VALUES('','$imageName','$image')";
$sendQuery=mysql_query($query);
if(!$sendQuery)
echo "This is embarressing. It didn't work";
else {
$lastid=mysql_insert_id();
echo "Image was uploaded. <br>Your image:";
echo "<img src=get.php?id=$lastid/>";
}
}
}
?>
</body>
</html>
and get.php:
<?php
//connect
mysql_connect("localhost", "root","") or die(mysql_error());
mysql_select_db("up") or die(mysql_error());
$id=mysql_real_escape_string($_REQUEST(['id']));
$imageQuery="SELECT * FROM store WHERE id=$id;";
$sendImageQuery=mysql_query($imageQuery);
$image=mysql_fetch_assoc($sendImageQuery);
$image=$image['image'];
header("Content-type: image/jpeg");
echo $image;
?>
PHP uploads, as stored in the ['tmp_name'] are TEMPORARY files, which are automatically deleted by PHP when the script ends/exits, unless you've taken measures to move it elsewhere. You'd need to have something more like
if ($_FILES['image']['error'] != UPLOAD_ERR_OK) {
... handle upload ...
move_uploaded_file($_FILES['image']['tmp_name'], "/path/in/your/document/root/$id.jpg");
} else {
die("Upload failed with error code: " . $_FILES['image']['error']);
}
first. Note the addition of the error check - NEVER assume that an upload succeeded.