Display all images from database (php) - php

I use this code to upload images in the database:
<?php
//Store the upload form
$UploadForm = " <form id='idForm' action='upload.php' method='post' enctype='multipart/form-data'>
<input type='file' name='image'/><br/><br/>
<input id='BTN' type='submit' value='Upload'/><br/><br/>
</form>";
//if logged in show the upload form
if($userid && $username){
echo $UploadForm;
// Connect to database
$con = mysqli_connect('***', '***', '***', '***_dbimage');
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
//file properties
if(isset($_FILES['image'])){
$file = $_FILES['image']['tmp_name'];
}
//if image selected
if(isset($file) && $file != ""){
$image = addslashes(file_get_contents($_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!";
header( "refresh:2;url=upload.php" );
}
else{
$qry = mysqli_query($con,"SELECT * FROM store WHERE name='$image_name'");
$Nrows = $qry->num_rows;
if( $Nrows == 0){
if(!$insert = mysqli_query($con,"INSERT INTO store VALUES ('','$image_name','$username','$image')")){
echo "We had problems uploading your file!";
header( "refresh:2;url=upload.php" );
}
else{
echo "Image $image_name uploaded!";
header( "refresh:2;url=upload.php" );
}
}
else{
echo "There is already an image uploaded with the name $image_name<br/>";
}
}
}
else{
echo "Please select an image";
}
mysqli_close($con);
}
else{
echo "You have to be logged in to upload!";
}
?>
And this code to display all images from the database:
// Connect to database
$con = mysqli_connect('***', '***', '***', '***_dbimage');
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$res = mysqli_query($con,'SELECT * FROM store');
while($row = $res->fetch_array()){
$image = $rows['image'];
echo "<img src='".$image."' />";
}
And I get something like tons of random symbols like diamonds with question marks in them and letters instead of my image. The scripts are not made by me. I just watched some tutorials and combined them and it seems that I didn't "combined" them properly. What am I doing wrong?
LATER EDIT:
HTML:
<img src="getImage.php?id=26"/>
PHP (getImage.php):
$con = mysqli_connect('***', '***', '***', '***_dbimage');
if(isset($_GET['id']))
{
$id = mysql_real_escape_string($_GET['id']);
$query = mysql_query("SELECT * FROM store WHERE id=$id");
while($row = mysql_fetch_assoc($query))
{
$imageData = $row['image'];
}
header("content-type:image/jpeg");
echo $imageData;
}
else
{
echo "Error!";
}
?>
Still can't get it to work! Help please!

I finaly did it!
This is the upload script:
<?php
//Store the upload form
$UploadForm = " <form id='idForm' action='upload.php' method='post' enctype='multipart/form-data'>
<input type='file' name='image'/><br/><br/>
<input id='BTN' type='submit' value='Upload'/><br/><br/>
</form>";
//if logged in show the upload form
if($userid && $username){
echo $UploadForm;
// Connect to database
$con = mysqli_connect('***', '***', '***', '***_dbimage');
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
//file properties
if(isset($_FILES['image'])){
$file = $_FILES['image']['tmp_name'];
}
//if image selected
if(isset($file) && $file != ""){
$image = mysqli_real_escape_string($con,file_get_contents($_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!";
header( "refresh:2;url=upload.php" );
}
else{
$qry = mysqli_query($con,"SELECT * FROM store WHERE name='$image_name'");
$Nrows = $qry->num_rows;
if( $Nrows == 0){
if(!$insert = mysqli_query($con,"INSERT INTO store VALUES ('','$image_name','$username','$image')")){
echo "We had problems uploading your file!";
header( "refresh:2;url=upload.php" );
}
else{
echo "Image $image_name uploaded!";
header( "refresh:2;url=upload.php" );
}
}
else{
echo "There is already an image uploaded with the name $image_name<br/>";
}
}
}
else{
echo "Please select an image";
}
mysqli_close($con);
}
else{
echo "You have to be logged in to upload!";
}
?>
Here is the diplay script:
$con = mysqli_connect('***', '***', '***', '***_dbimage');
$query = mysqli_query($con,"SELECT id FROM store");
while($row = mysqli_fetch_assoc($query))
{
$IDstore = $row['id'];
echo "<img src='getImage.php?id=".$IDstore."'/>";
}
And the "getImage.php":
<?php
$con = mysqli_connect('***', '***', '***', '***_dbimage');
if(isset($_GET['id']))
{
$id = mysqli_real_escape_string($con,$_GET['id']);
$query = mysqli_query($con,"SELECT * FROM store WHERE id=$id");
while($row = mysqli_fetch_assoc($query))
{
$imageData = $row['image'];
}
header("content-type:image/jpeg");
echo $imageData;
}
else
{
echo "Error!";
}
?>
I hope it will help someone cause it's ready to use now. :)

Related

Trying for users to add profile picture php

I want a logged in user to add a profile picture. if the user havent added a picture, the default image should display.
here is the code I tried. The default image is not showing and it is displaying the amount of users in the database. I know I should use prepared statements, but dont know how to with adding a file.
<?php
session_start();
$db = mysqli_connect('localhost', 'root', '', 'pt');
if(isset($_POST['upload_submit'])){
$file = $_FILES['file'];
$fileName = $_FILES['file']['name'];
$fileTmp = $_FILES['file']['tmp_name'];
$fileSize = $_FILES['file']['size'];
$filesError = $_FILES['file']['error'];
$fileType = $_FILES['file']['type'];
$fileExt = explode('.',$_FILES['file']['name']);
$fileActualExt = strtolower(end($fileExt));
$allowed = array('jpg','jpeg','png','pdf');
if(in_array($fileActualExt,$allowed)){
if($_FILES['file']['error'] === 0){
if($_FILES['file']['size'] < 1000000){
$fileNameNew =
"profile".$_SESSION['username'].".".$fileActualExt;
$fileDestination = 'uploads/'.$fileNameNew;
move_uploaded_file($_FILES['file']
['tmp_name'],$fileDestination);
$sql = "UPDATE users SET status = 0 WHERE
username='$_SESSION[username]';";
$result = mysqli_query($db, $sql);
header("Location: pic.php");
}else{
echo "Your file is too big!";
}
}else{
echo "You have an error uploading your file!";
}
}else{
echo "You cannot upload files of this type!";
}
}
?>
<?php
$sql = "SELECT * from users";
$result = mysqli_query($db, $sql);
if(mysqli_num_rows($result)> 0){
while ($row = mysqli_fetch_assoc($result)){
$sqlimg = "SELECT * FROM users WHERE
username='$_SESSION[username]'";
$resultimg=mysqli_query($db,$sqlimg);
while($rowimg = mysqli_fetch_assoc($resultimg)){
echo "<div class=container>";
if($rowimg['status'] == 0){
echo "<img src=
'uploads/profile".$_SESSION['username'].".jpg'>";
}else{
echo "<img src='uploads/male.jpg'>";
}
echo "<p>".$_SESSION['username']."</p>";
echo "</div>";
}
}
}else{
echo "There are no users yet!";
}
if(isset($_SESSION['username'])){
echo "<form action='pic.php'
method='POST'enctype='mutlipart/form-
data'>
<input type='file' name='file'>
<button type='submit' name='upload_submit'>Upload</button>
</form>";
}else {
echo "You are not logged in!";
}
?>

Old picture is missing

So I have "staff" table in database i.e. StaffName, StaffAddress and StaffProfilePicture etc. Updating works fine on name, address but not the picure. The old picture seems to be missing from the database eventhough I don't upload a new one.
if(isset($_POST['submit'])){
$target_dir = "images/staff/";
$target_dir = $target_dir . basename($_FILES["new_profilepicture"]["name"]);
$uploadOk=1;
if (file_exists($target_dir . $_FILES["new_profilepicture"]["name"])) {
//echo "Sorry, file already exists.";
$uploadOk = 0;
}
if ($uploadOk==0) {
//echo "Sorry, your file was not uploaded.";
}
else {
if (move_uploaded_file($_FILES["new_profilepicture"]["tmp_name"], $target_dir)) {
$imageup = $target_dir;
//echo "<img src='" . $imageup . "' />";
} else {
//echo "Sorry, there was an error uploading your file.";
}
}
$_var1 = $_POST['new_name'];
$_var2 = $_POST['new_email'];
$_var3 = $_POST['new_password'];
$_var4 = $_POST['new_contactno'];
$_var5 = $_POST['new_icno'];
$_var6 = $_POST['new_address'];
$_var7 = $_POST['new_status'];
$_var8 = $imageup;
$query1 = $mysqli->query("UPDATE staff
SET StaffName='$_var1', StaffEmail='$_var2', StaffPassword='$_var3', StaffContactNo='$_var4', StaffICNo='$_var5', StaffAddress='$_var6', StaffStatus='$_var7', StaffProfilePicture='$_var8'
WHERE StaffID='$staffID'");
$success = mysql_query($query1);//is mysql query working?
if($success){
//$oldprofilepicture = $staff['StaffProfilePicture'];
//if(file_exists($oldprofilepicture)){
//unlink($oldprofilepicture);//delete now
echo "success";
header('location:staff_profile.php');
die;
}else{
echo "failed";
}
}
Below is the HTML form for the picture
<tr>
<td width="170">Old Profile Picture:</td>
<td><img src="<?php echo $profilepicture ?>" width="100" height="80" /><br><br>
<input type="file" name="new_profilepicture" />
</tr>
How can I make the old/existed picture stay?
On your query you have:
StaffProfilePicture='$_var8'
so it still updates the database and since $imageup is empty/undefined so is $_var8 and it will update the database with empty value.
So add an if condition:
$_var8 = $imageup;
if($_var8 != '') {
$query1 = $mysqli->query("UPDATE staff SET StaffName='$_var1', StaffEmail='$_var2', StaffPassword='$_var3', StaffContactNo='$_var4', StaffICNo='$_var5', StaffAddress='$_var6', StaffStatus='$_var7', StaffProfilePicture='$_var8' WHERE StaffID='$staffID'");
} else {
$query1 = $mysqli->query("UPDATE staff SET StaffName='$_var1', StaffEmail='$_var2', StaffPassword='$_var3', StaffContactNo='$_var4', StaffICNo='$_var5', StaffAddress='$_var6', StaffStatus='$_var7' WHERE StaffID='$staffID'");
}
or you can do it other ways but that's where your problem is that you're losing your old image. Hope it helps.
Cheers.

How to upload ONLY images in database

I want to upload ONLY pictures , in the database using php.
What I tried is,
<?php
if (isset($_POST['Upload'])) {
$con = mysql_connect("localhost", "root", "");
if (!$con) {
die('Could not connect: ' . mysql_error());
}
mysql_select_db("iis", $con);
$image = $_FILES["product_image"]["name"];
$imageType = mysql_real_escape_string($_FILES["product_image"]["type"]);
if (substr($imageType, 0, 5) == "image") {
if (!file_exists("product_images")) {
mkdir("product_images");
}
if ($_FILES["product_image"]["error"] > 0) {
$error = "ERROR Return Code :" . $_FILES["product_image"]["error"] . "<br />";
} else {
move_uploaded_file($_FILES["product_image"]["tmp_name"], "product_images/" . $_FILES["product_image"]["name"]);
}
}
$UserName = $_SESSION['id'];
$product_image = ("product_images/" . $_FILES["product_image"]["name"]);
mysql_query("INSERT INTO `feedbackzxc` VALUES ('', '$UserName', '$product_image')");
echo "Image Uploaded!";
} else {
echo "Only images are allowed";
}
?>
But when I upload a file other than images it doesn't show the error message. How can I make it show error message if a file other than an image is uploaded?
Your else block where the message Only images are allowed is shown must be located after the if block that check this: substr($imageType,0,5) == "image"
if(substr($imageType,0,5) == "image"){
if(!file_exists("product_images"))
{
mkdir("product_images");
}
if($_FILES["product_image"]["error"] > 0)
{
$error = "ERROR Return Code :" . $_FILES["product_image"]["error"] . "<br />";
}
else
{
move_uploaded_file($_FILES["product_image"]["tmp_name"], "product_images/".
$_FILES["product_image"]["name"]);
}
}
else
{
echo "Only images are allowed";
}

Insert image path(Browse image folder location) in database and retrieve it

This is the code what I get from google search. But I don't know that will be the img.php . I search in google but unable to do this problem.
HTML :
< form action =" img.php " method = "POST" enctype = "multipart/form-data">
< input type="file" name = "myfile" />
< input type = "submit" value="upload" />
< /form>
PHP:
mysql_connect("localhost","root","") or die("cant connect to server.");
mysql_select_db("databaseimage") or die("cant connect to database");
echo "name:";
echo $name = $_FILES['myfile']['name'];
echo "type ";
echo $type = $_FILES['myfile']['type'];
echo "<BR>";echo "Size: ";
echo $size = $_FILES['myfile']['size'];
echo "temp: ";
echo $temp = $_FILES['myfile']['tmp_name'];
echo "error code: ";
echo $error = $_FILES['myfile']['error'];
echo "file contents: ";
echo $file_contents = addslashes(file_get_contents($_FILES['myfile']['tmp_name']));
echo "<BR>";
if (!$insert = mysql_query("INSERT INTO table1 VALUES ('','$name','$file_contents')"))
echo "problem uploading file";
else {$last_id = mysql_insert_id();
echo "Image uploaded.";
echo "<BR>";
echo "<img src=get.php?id=$last_id>";
}
Save your php file as a img.php and you have a get.php and get.php have code like,
if(isset($_REQUEST['id'])){
mysql_connect("localhost","root","") or die("cant connect to server.");
mysql_select_db("databaseimage") or die("cant connect to database");
$sql_result = mysql_query("SELECT name FROM table1 WHERE id= $_REQUEST['id']");
$row = mysql_fetch_row($sql_result);
echo $row[0];
}

"Blog Post" show from Mysql Database wtih Image

How can I show my all "blog post" with images? Example:
Mysql table:
post_id | user_id | subject | message | image | img_name.
What is the php code to display all my posts with images in the index page? I used the following code but it doesn't display images, it shows only data. I would like to see something like this:
image | message is here
image | message is here
image | message is here
I used 3 pages
add_post.php(Html form)
add_post_process.php(process the add_post.php)
index.php (which shows my all post)
add_post_process.php:
<?php
include "db.php";
#$file = addslashes($_FILES['image']['tmp_name']);
$lastid= mysql_insert_id();
#$img = addslashes(file_get_contents($_FILES['image']['tmp_name']));
$img_name = addslashes($_FILES['image']['name']);
#$img_size = getimagesize($_FILES['image']['tmp_name']);
$upload_path = './blogpostimg/';
$post_id = addslashes($_POST['post_id']);
$user_id = addslashes($_POST['user_id']);
$subject = addslashes($_POST['subject']);
$message = addslashes($_POST['message']);
$cat_id = addslashes($_POST['cat_id']);
$cat_name = addslashes($_POST['cat_name']);
$comment_count = addslashes($_POST['comment_count']);
$ch_img = addslashes($_FILES['image']['name']);
$query = "SELECT img_name FROM blog_post WHERE img_name = '$ch_img';";
$result = mysql_query($query) or die (mysql_error());
if(isset($subject, $message))
{
$errors = array();
if(empty($subject) && empty($message) && empty($file))
{
$errors[] ='all field required';
}
else
{
if(empty($subject))
$errors[] = 'Subejct requried';
if (empty($message))
$errors[] = 'message required';
if(empty($file))
$errors[] ="SORRY, you have to be upload a image";
elseif($img_size == FALSE)
{
$errors[] ="That's not an image";
}
else
{
if(mysql_num_rows($result) != 0)
$errors[] = " You have to change this image name, already exit in our database";
}
}
if(!empty($errors))
{
foreach($errors as $error)
{
echo "<ul>";
echo "<strong><font color=red><li>$error</li></font></strong><br/>";
echo "</ul>";
}
}
else
{
if(!move_uploaded_file($_FILES['image']['tmp_name'],$upload_path . $img_name))
{
die('File Not Uploading');
}
else
{
$lastid = mysql_insert_id();
$query = mysql_query("INSERT INTO blog_post VALUES ('', '', '$subject',
'$img','$img_name','$message','$cat_id','$cat_name','',NOW() )");
if($query)
echo "Successfully uploaeded your post";
else
{
echo "Something is wrong to Upload";
}
}
}
}
?>
index.php
<?php
include "db/db.php";
$upload_path = "/secure/content/blogpostimg";
$sql= mysql_query("SELECT * FROM blog_post");
while ($rel = mysql_fetch_assoc($sql))
{
$id = $rel['post_id'];
$sub = $rel['subject'];
$imgname = $rel['img_name'];
$img = $rel ['image'];
$msg = $rel['message'];
$date = $rel['date'];
echo "<h1>". "$sub" ."</h1>". "<br/>";
echo "$imgname" ."<br/>";
echo '<img src="$upload_path " />';
echo "$msg" . "<br/>";
echo "$date" . "<br/>";
echo "<hr/>";
echo "<br/>";
}
?>
The mysql table structure is
post_id(int)
User_id(int)
subject(varchar)
image(blob)
img_name(varchar)
message(text)
change
echo '<img src="$upload_path " />';
to
echo '<img src="' . $upload_path . '/' . $img . '" />';
that should do the trick..
I don't now if it matters in performanceways.. but howcome you use blob instead of a varchar.. 255 characters for a filename should be enough.
In your index.php you have <img src="$upload_path" />. Instead of $upload_path, src needs to be the URL to your image.
I just noticed that you are storing the image itself in the database. There is no need to do this if you move it to a publicly accessible directory, e.g. /var/www/images/myimage.jpg

Categories