Trouble recalling image from file system of server - php

So I've finally got my images to be stored in folders on my server when a user uploads a photo. What I need to figure out now, is how to users can upload that photo (to the file system folder), then have that photo automatically be shown on index.php page, within the content wrapper. Any help is great.
The image I want displayed would be inside the image div, which is inside the photo div,and is above the imageInfo div, which contains a description of the image.
Here's the code for my index.php page (it already has a sample image there for reference):
<div id="contentWrapper">
<?php echo "<div id='photo'><div id='image'><img src='https://i.imgur.com/1QJFnJz.jpg'><div id='imageInfo'></div></div></div>";?>
</div>
Here is the code for my image upload form:
<body>
<div id="contentWrapper">
<img style="margin-left:150px ; margin-top:70px" src="http://i.imgur.com/YjvuqaP.jpg" height="100">
<div id="postForm">
<form action="posts_check.php" method="POST" name="posts_form" id="posts_form" onSubmit="return validateFrom()" enctype="multipart/form-data">
<input type="file" name="image" id="image"><br>
<textarea name="description" id="description" placeholder="Enter a description of your work here...";></textarea><br>
<input type="submit" name="upload" id="upload" value="Upload">
</form>
</div>
<h2 style="font-family:Arial ; color:#9b6bb4">Before you upload your file:</h2>
<ul style="font-family:Arial">
<li>Your file must be smaller than 1MB, so if you need to compress your photo, visit <a style="text-decoration:none ; color:#9176FF" href="http://jpeg-optimizer.com/">JPEG-Optimizer</a></li><br>
<li>Make sure that your file is 'at least' <em><strong>480px</strong></em> wide. (If not, the image will look weird when uploaded)</li><br>
<li>Make sure that you are the owner of the work that you are uploading. (Copyright suits suck)</li><br>
<li>Make sure you include a detailed description of the work to give others an idea of how you did it.</li>
</ul>
</div>
Here is the code to send the uploaded image to a folder on the server:
<?php
session_start();
if(!isset($_SESSION['username'])) {
header('location: must_login.php');
}
$conn = mysqli_connect("localhost","root","") or die ("No SQLI");
mysqli_select_db($conn, "sample") or die ("No DB");
if (isset($_FILES['image']) && ($_FILES['image']['size'] < 2097152) && (in_array($_FILES['image']['type'], array('image/jpeg', 'image/png', 'image/jpg', 'image/gif')))) {
$chars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
$rand_dir_name = substr(str_shuffle($chars), 0, 15);
mkdir("photos/$rand_dir_name");
if (file_exists("photos/$rand_dir_name/".$_FILES["image"]["name"]))
{
echo $_FILES["image"]["name"]." Already exists";
}
else
{
move_uploaded_file($_FILES["image"]["tmp_name"],"photos/$rand_dir_name/".$_FILES["image"]["name"]);
//echo "Uploaded and stored in: phoyoss/$rand_dir_name/".#$_FILES["image"]["name"];
$username = 'ralston3';
$description = $_POST['description'];
$image_name = $_FILES['image']['name'];
$image_id_before_md5 = "$rand_dir_name/$image_name";
$image_id = md5($image_id_before_md5);
$date = date('Y-m-d');
$sqli = "INSERT INTO `photos` (username, description, image_name, image_id, post_date) VALUES ('ralston3','$description','$image_name','$image_id','$date')";
mysqli_query($conn, $sqli) or die ("No query");
header('location:index.php');
//$profile_pic_name = #$_FILES["profilepic"]["name"];
//$img_id_before_md5 = "$rand_dir_name/$profile_pic_name";
//$img_id = md5($img_id_before_md5);
//$profile_pic_query = mysql_query("INSERT INTO photos VALUES ('','test','$user','$date','$description','http://localhost/tutorials/findFriends/userdata/user_photos/$rand_dir_name/$profile_pic_name','no','$img_id')");
//header("Location: upload_photo.php");
}
} else {
header('location:error.php');
}
?>

<?php
$sql=mysql_query("select id, username, description, image_name, image_id, post_date from photos ORDER BY id DESC");
echo "<div id='contentWrapper'>";
while($image=mysql_fetch_array($sql)){
echo "<div id='photo'><div id='image'><img src='https://yoursite.com/photos/$image[$image_id]/$image[$image_name]'><div id='imageInfo'></div></div></div>";
}
echo "</div>";
?>
note you must add id identifier as image id (create new id field with INT) image_id you mentioned abou is handling folder name, so it must contain random value so cannot be used to ORDER method

Related

image gallery insetring with condition on update page

m creating simple blog site, in creating new page, i have insert image gallery too. page and gallery both have two different table as i couldn’t figure out how to insert gallery into single table (means gallery section in pages table, so i created two tables)
What im trying to achieve in update pages is that check if image is insert or not in update page. if image is insert then display image else allow user to upload image in update page
table_name = english_version (table for page)
table for page
table_name = english_gallery (table for gallery)
table fro gallery
*Where image_id = id (id from english_version)
so when user creates new page and sumbit, it is send to update page:
header(“Location:./update.php?update=$lastenterid”);
die();
so, if user forget to insert image for gallery then i want to give option for image upload in update pages…
if(isset($_GET['update'])){
$update_id = intval($_GET['update']);
$update = $conn->query("SELECT * FROM english_version WHERE id = $update_id ");
while($rows = $update->fetch(PDO::FETCH_OBJ) ):
$id = $rows->id;
$title = $rows->title;
$content = $rows->content;
endwhile;
}
checking if image is insert or not
<form action="" method="post">
<!-- english-version -->
<input type="hidden" name="id" value="<?php echo $id;?>">
<div class="form-group">
<input type="text" name="title" class="form-control mt-3" value="<?php echo $title?>">
</div>
<div class="form-group">
<textarea class="form-control" name="content" id="" cols="30" rows="10"><?php echo $content;?></textarea>
</div>
<div class="form-group">
<?php
//getting data from english_gallery (table for gallery)
$gallery = $conn->query("SELECT * FROM english_gallery WHERE image_id = $update_id");
while($rows_gal = $gallery->fetch(PDO::FETCH_OBJ) ):
$id = $rows_gal->gallery_id;
$image_id = $rows_gal->image_id;
$image = $rows_gal->image;
//check if image_id == $update_id (where $update is id of (primary_key) english_version (table for page))
if($image_id == $update_id ){ ?>
<div class="image-gallery">
<img src="<?php echo $image;?>" alt="">
</div>
<?php
}else{
$targetDir = "image/";
$allowTypes = array('jpg','png','jpeg','gif');
$images_arr = array();
foreach($_FILES['images']['name'] as $key=>$val){
$image_name = $_FILES['images']['name'][$key];
$tmp_name = $_FILES['images']['tmp_name'][$key];
$size = $_FILES['images']['size'][$key];
$type = $_FILES['images']['type'][$key];
$error = $_FILES['images']['error'][$key];
// File upload path
$fileName = basename($_FILES['images']['name'][$key]);
$targetFilePath = $targetDir . $fileName;
// Check whether file type is valid
$fileType = pathinfo($targetFilePath,PATHINFO_EXTENSION);
if(in_array($fileType, $allowTypes)){
// Store images on the server
if(move_uploaded_file($_FILES['images']['tmp_name'][$key],$targetFilePath)){
$images_arr[] = $targetFilePath;
$insert = $conn->query("INSERT into english_gallery (image_id,image) VALUES ('$update_id','$targetFilePath')");
$galleryid = $conn->lastInsertId();
if($insert){
$count = $key + 1;
$statusMsg = " ".$count. " image file has been uploaded successfully.";
}else{
$statusMsg = "Failed to upload image";
}
}else{
$statusMsg = "Sorry, there was an error uploading your file.";
}
}else{
$statusMsg = 'Sorry, only JPG, JPEG, PNG, & GIF files are allowed to upload.';
}
}//multiple_image upload starts
?>
<!-- if image_id !== $update then display multi-image upload section -->
<div class="form-group">
<input type="file" name="images[]" multiple>
</div>
<?php
}
endwhile;
?>
</div>
<div class="form-group">
<input type="submit" value="Update" name="update" class="btn btn-primary">
</div>
<!-- english-version -->
if($image_id == $update_id ){
if there is image its displaying image but if there no image its not displaying input option for image upload
upload image
if think else conditions is not working because $image_id stores id of (primary_key) english_version (table for page)) it’s checking for the id which is never created…
so, how can i get the condition, where if user have insert image then image will displayed else user will get option for image uploading…

How do I add an image to a sql database

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";
}
}
?>

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"]; ?>">

Image reselect php

I have a table where each row has an image and some text. Currently, when I update the content without selecting an image, the database field for the image gets cleared out. However, I want to keep the old image if there's no image selected.
How can I accomplish this?
As a note, I know that mysql_* functions are deprecated.
<?php
include("db/db.php");
$select_db = "select * from aboutus WHERE id=1";
$run_news = mysql_query($select_db);
while ($row = mysql_fetch_array($run_news)) {
$id = $row['id'];
$image = $row['image'];
$content = $row['content'];
}
?>
<div class="box box-primary">
<div class="box-header with-border">
<h3 class="box-title">Update About Content</h3>
</div>
<!-- /.box-header -->
<!-- form start -->
<form role="form" method="post" action="aboutcontent.php?id=1" enctype="multipart/form-data">
<div class="box-body">
<div class="form-group">
<label for="exampleInputFile">Reselect Image *(H=530px, W=800px)</label>
<input type="file" name="user_image" id="exampleInputFile">
</div>
<div class="form-group">
<label >Content</label><br>
<textarea name="content" class="tinymce" class="form-control" rows="15"><?php echo $content; ?></textarea>
</div>
</div>
<!-- /.box-body -->
<div class="box-footer">
<button type="submit" name="update" class="btn btn-primary">Update</button>
</div>
</form>
</div>
<?php
include("db/db.php");
// Code for UPDATE button
if (isset($_POST['update'])) {
$content = $_POST['content'];
$imgFile = $_FILES['user_image']['name'];
$tmp_dir = $_FILES['user_image']['tmp_name'];
$imgSize = $_FILES['user_image']['size'];
if ($imgFile) {
$upload_dir = 'images/about/'; // upload directory
$imgExt = strtolower(pathinfo($imgFile, PATHINFO_EXTENSION)); // get image extension
$valid_extensions = array('jpeg', 'jpg', 'png', 'gif'); // valid extensions
$userpic = rand(1000, 1000000) . "." . $imgExt;
if (in_array($imgExt, $valid_extensions)) {
if ($imgSize < 5000000) {
unlink($upload_dir . $row['image']);
move_uploaded_file($tmp_dir, $upload_dir . $userpic);
}
else {
$errMSG = "Sorry, your file is too large it should be less then 5MB";
}
}
else {
$errMSG = "Sorry, only JPG, JPEG, PNG & GIF files are allowed.";
}
}
else {
// if no image selected the old image remain as it is.
$userpic = $row['image']; // old image from database
}
// if no error occured, continue ....
$sql = "UPDATE aboutus SET image='$userpic', content='$content' WHERE id=1";
$query = mysql_query($sql);
if (!$query) {
die('Invalid query: ' . mysql_error());
}
else {
echo "<script>alert('Successfully Updated!!!'); window.location='index.php?aboutcontent'</script>";
}
}
?>
The problem can easily be solved by checking if a file was submitted or not:
if(!empty($userpic)){
// SQL update here
} else {
// No file submitted so don't update
}
The reason you were getting empty mysql fields is because you were updating the field with an empty variable.
Since I can't comment yet, when you submit without an image are you landing in the if or else statement (place a die('some content) in each part) to figure this out. If you are not making it to the else, try:
//initialize error message
$errMSG = '';
//this error means 'There is no error, the file uploaded with success'
if($_FILES['user_image']['error'] == 0){
//rest of logic to get the filename and move files stuff
}
else{
$userpic = $row['image'];
}
//you dont want to update database if there are errors
if(errMSG = ''{
$sql = "UPDATE aboutus SET image='$userpic', content='$content' WHERE id=1";
}
OR just make two different database calls, one for when you have an image and one for when you dont
if($_FILES['user_image']['error'] == 0){
//rest of logic to get the filename and move files stuff
//if everything else is true (has filename and correct file size)
//you dont want to update database if there are errors
if(errMSG = ''{
$sql = "UPDATE aboutus SET image='$userpic', content='$content' WHERE id=1";
}
$sql = "UPDATE aboutus SET image='$userpic', content='$content' WHERE id=1";
}
else{
$userpic = $row['image'];
$sql = "UPDATE aboutus SET content='$content' WHERE id=1";
}
http://php.net/manual/en/features.file-upload.errors.php

How to solve broken image displayed using php after upload to database

I try upload image to mysql database and display it along with the description of image using php. After i upload the image and display it , a broken image was displayed but the description of the image was displayed without any error. How can I solve this problem ? Appreciate your help
<?php
$msg = "";
//if upload button is pressed
if(isset($_POST['upload']))
{
// the path to store the uploaded image
$target = "images/".basename($_FILES['image']['name']);
// connect to database
$db = mysqli_connect("localhost","root","","product");
// Get all the submitted data from the form
$image = $_FILES['image']['name'];
$text = $_POST['text'];
$sql = "INSERT INTO product_list (image, text) VALUES ('$image','$text')";
mysqli_query($db,$sql); // stores the submitted data into the database table : product_list
// move uploaded image to the folder : image
if (move_uploaded_file($_FILES['image']['tmp_name'],$target))
{
$msg = "Image and text uploaded successfully";
}else
{
$msg = "There was a problem uploading image";
}
}
?>
<!DOCTYPE html>
<html>
<head>
<title>Image Upload With Description</title>
<link rel="stylesheet" type="text/css" href="formstyle.css">
</head>
<body>
<div id="content">
<?php
$db = mysqli_connect("localhost","root","","product");
$sql = "SELECT * FROM product_list";
$result = mysqli_query($db, $sql);
while ($row = mysqli_fetch_array($result))
{
echo "<div id='img_div'>";
echo "<img src='".$row['image']."'>";
echo "<p>".$row['text']."</p>";
echo "</div>";
}
?>
<form method="post" action="try.php" enctype="multipart/form-data">
<input type="hidden" name="size" value="1000000">
<div>
<input type="file" name="image">
</div>
<div>
<textarea name="text" cols="40" rows="4" placeholder="Details of product"></textarea>
</div>
<div>
<input type="submit" name="upload" value="Upload Image">
</div>
</form>
</div>
</body>
</html>
This is my result :
You are storing it in the DB without the images directory. You either need to store it with that, or always remember to call it that way in your image calls.
echo "<img src='images/".$row['image']."'>";
or make your the record you are writing the same as the filesystem location.
$image = 'images/' . $_FILES['image']['name'];
Note you are open to SQL injections and file inclusion injections with this code.
try this
<?php
$msg = "";
//if upload button is pressed
if(isset($_POST['upload']))
{
// the path to store the uploaded image
$destination_path = getcwd().DIRECTORY_SEPARATOR;
$target_path = $destination_path . basename( $_FILES["image"]["name"]);
// connect to database
$db = mysqli_connect("localhost","root","","product");
// Get all the submitted data from the form
$image = $_FILES['image']['name'];
$text = $_POST['text'];
$sql = "INSERT INTO product_list (image, text) VALUES ('$image','$text')";
mysqli_query($db,$sql); // stores the submitted data into the database table : product_list
//#move_uploaded_file($_FILES['image']['tmp_name'], $target_path)
// move uploaded image to the folder : image
if (move_uploaded_file($_FILES['image']['tmp_name'],$target_path))
{
$msg = "Image and text uploaded successfully";
}else
{
$msg = "There was a problem uploading image";
}
}
?>
<!DOCTYPE html>
<html>
<head>
<title>Image Upload With Description</title>
<link rel="stylesheet" type="text/css" href="formstyle.css">
</head>
<body>
<div id="content">
<?php
$db = mysqli_connect("localhost","root","","product");
$sql = "SELECT * FROM product_list";
$result = mysqli_query($db, $sql);
while ($row = mysqli_fetch_array($result))
{
echo "<div id='img_div'>";
echo "<img src='".$row['image']."'>";
echo "<p>".$row['text']."</p>";
echo "</div>";
}
?>
<form method="post" action="index.php" enctype="multipart/form-data">
<input type="hidden" name="size" value="1000000">
<div>
<input type="file" name="image">
</div>
<div>
<textarea name="text" cols="40" rows="4" placeholder="Details of product"></textarea>
</div>
<div>
<input type="submit" name="upload" value="Upload Image">
</div>
</form>
</div>
</body>
</html>

Categories