How to upload and insert multiple images in PHP and mysql database - php

I am a beginner in PHP. I encoded some images in a base64String. All images are successfully decoding in the specified folder. My problem is am only able to record one image/path in the database. Somebody help me to come up with the PHP to insert all images paths in one row in the database.
here is the php code
<?PHP
if(isset($_POST['image']))
{
$image = $_POST['image'];
$identity = $_POST['id'];
$username = $_POST['username'];
//create unique image file name based on micro time and date
$now = DateTime::createFromFormat('U.u', microtime(true));
$id = rand(1000000, 10000000000);
$id2=rand(1000000, 10000000000);
$upload_folder = "upload";
$id="$id$id2";
$path = "$upload_folder/$id.jpeg";
if(file_put_contents($path, base64_decode($image)) != false){
echo "uploaded_success";
$sql = "UPDATE apartment SET Image_path = '$path' WHERE apart_username
='$username' AND id = '$identity'";
mysqli_query($conn, $sql);
}
else{
echo "uploaded_failed";
}
exit;
}
else{
echo "images_not_in";
exit;
}
?>

You need some sort of loop...all I did in the example below was instead of making a single variable called image I made a array called $imagesArr. And I added a foreach loop on the imagesArr so it will run the code you wrote for each image you input into that array. I also killed the exit at the end as that would stop the loop. That should work
<?PHP
if(isset($_POST['image']))
{
//$image = $_POST['image']; - I commented this out
$imagesArr = array('image1.jpeg','image2.jpeg','image3.jpeg'); //etc. put all of your images here into this array
$identity = $_POST['id'];
$username = $_POST['username'];
foreach ($imagesArr as $key => $image) {
//create unique image file name based on micro time and date
$now = DateTime::createFromFormat('U.u', microtime(true));
$id = rand(1000000, 10000000000);
$id2=rand(1000000, 10000000000);
$upload_folder = "upload";
$id="$id$id2";
$path = "$upload_folder/$id.jpeg";
if(file_put_contents($path, base64_decode($image)) != false){
echo "uploaded_success";
$sql = "UPDATE apartment SET Image_path = '$path' WHERE apart_username
='$username' AND id = '$identity'";
mysqli_query($conn, $sql);
}
else{
echo "uploaded_failed";
}
}
else{
echo "images_not_in";
}
}

Related

Retrieving image from the database and updating the image or uploading another file

I have an upload function where the image is uploaded into the database then I want to echo the image but the problem is if I update the image, it won't show but if it is the first upload the image is showing here's how I upload the image
include('phpqrcode/qrlib.php');
//start of register function
if (isset($_POST['student-registration'])) {
// get image - student picture
$check = getimagesize($_FILES["image"]["tmp_name"]);
if($check !== false){
$image = $_FILES['image']['tmp_name'];
$imgContent = addslashes(file_get_contents($image));
}
else{
array_push($errors, "Please select an image to upload");
}
here's how I echo the image please note that I echo the image in a different file i'm including the file where the upload function is located
<?php echo '<img src="data:image/jpeg;base64,'.base64_encode($image).'" style ="width:200px; height:200px;"/>'; ?>
<?php
i only have one data field for the image and it is called image from userinfo table
here's how I fetch the arrays from my database table
$UserID = $_POST['UserID'];
// mysql search query
$query = "SELECT * FROM userinfo WHERE UserID = '$UserID' LIMIT 1";
$result = mysqli_query($db, $query);
// if code exist
// show data in inputs
if(mysqli_num_rows( $result) > 0)
{
while ($row = mysqli_fetch_array($result))
{
$UserType= $row['UserType'];
if ($UserType != "Student")
{
echo '<span style="color:#FF0000;text-align:center;">Oppss... Student ID not FOUND!</span>';
$UserID = "";
}
else //get data from database to retrieve and display in students registration form
{
$StudName = $row['LName'].","." " .$row['FName']." ".$row['MName'];
$UserType= $row['UserType'];
$UserID = $row['UserID'];
$FName = $row['FName'];
$MName = $row['MName'];
$LName = $row['LName'];
$EName = $row['EName'];
$Gender = $row['Gender'];
$Address = $row['Address'];
$ContactNo = $row['ContactNo'];
$EmailAddress = $row['EmailAddress'];
$College = '<option value="' . $row['College'] . '">' ;
$Department = $row['Department'];
$Course = $row['Course'];
$YearLevel = $row['YearLevel'];
$ParentName = $row['ParentName'];
$ParentEmail = $row['ParentEmail'];
$ParentContact = $row['ParentContact'];
$image = $row['image']; // image from the database
}
}
}
thanks in advance
When querying your DB you are putting in $image the image's content.
When updating image, you are putting in $image the image's name.
This is why your image is not displaying after update.
You need to:
OR put image content in $image while updating
- $image = $_FILES['image']['tmp_name'];
- $imgContent = addslashes(file_get_contents($image));
+ $img_name = $_FILES['image']['tmp_name'];
+ $image = file_get_contents($img_name);
+ $imgContent = addslashes($image);
OR execute your query part after update.

how to use old profile picture if no image selected in php

this is my code updating data. How is it possible to use old image if no image is selected?
its a profile page when someone updates his profile but don't select the image for update then old image should be remained there..
<?php
if(isset($_POST['update_user'])){
//getting text data from field
$update_id = $user_id;
$fullname = $_POST['fullname'];
$designation = $_POST['designation'];
$username = $_POST['username'];
$location="images/users/";
$name=$_FILES['user_img']['name'];
$temp_name=$_FILES['user_img']['tmp_name'];
if(isset($name)){
move_uploaded_file($temp_name,$location.$name);
}
else
{
echo $user_img;
}
$update_product = "update user set FullName='$fullname',Designation='$designation',UserName='$username',User_Pic='$name' where Id='$update_id'";
$run_product = mysqli_query($con, $update_product);
if ($run_product){
echo"<scripy>alert('Update Successful')</script>";
echo "<script>window.open('user_manage.php','_self') </script>";
}
}
?>
First, you need to fetch the existing user details from the database and check if the user already has a profile picture.
Next, if the user has uploaded a new image, then you can delete the old profile picture using unlink() function. If the user has not uploaded a new picture, you can retain the old picture.
See the code below.
<?php
if(isset($_POST['update_user'])){
//getting text data from field
$update_id = $user_id;
$fullname = $_POST['fullname'];
$designation = $_POST['designation'];
$username = $_POST['username'];
$location="images/users/";
//Fetch user details
$query = "SELECT User_Pic FROM user WHERE Id=" . $update_id;
$result = mysqli_query($con, $query);
$row = false;
if (mysqli_num_rows($result) > 0) {
$row = mysqli_fetch_assoc($result);
}
if (isset($_FILES['user_img'])) { //User uploaded new image
if ($row) {
unlink($location . $row['User_Pic']); //Delete old pic
}
$name=$_FILES['user_img']['name'];
$temp_name=$_FILES['user_img']['tmp_name'];
move_uploaded_file($temp_name,$location.$name);
$update_product = "update user set FullName='$fullname',Designation='$designation',UserName='$username',User_Pic='$name' where Id='$update_id'";
} else { //User did not upload image
if ($row) {
echo $location . $row['User_Pic']; //Echo current image path
}
$update_product = "update user set FullName='$fullname',Designation='$designation',UserName='$username' where Id='$update_id'";
}
$run_product = mysqli_query($con, $update_product);
if ($run_product){
echo"<scripy>alert('Update Successful')</script>";
echo "<script>window.open('user_manage.php','_self') </script>";
}
}
?>
Please note that the code shown here does not change the filename when storing the files on the server. This will cause problems when two person upload pictures with same filename. You need to implement an appropriate solution for that.

passed variable returns empty in url on target page

I am going out of my mind as it is. I am trying to pass a variable from a page that shows all albums thumbnail image and name to a page that will display all the pictures in that gallery using that passed variable, but the variable is empty in the url on the target page. I have seen similar cases on the web and on this site and I've applied the suggestions but it's still the same. Here is the code that lists the thumbnail and passes the variable(id).
<?php
include ("config.php");
$conn = mysqli_connect(DB_DSN,DB_USERNAME,DB_PASSWORD,dbname);
$albums = mysqli_query($conn,"SELECT * FROM albums");
if (mysqli_num_rows($albums) == 0) {
echo "You have no album to display. Please upload an album using the form above to get started. ";
}
else{
echo "Albums created so far:<br><br>";
echo "<table rows = '4'><tr>";
while ($thumb = mysqli_fetch_array($albums)) {
echo '<td><a href ="view.php?id="'.$thumb['id'].'"/><img src = "'.$thumb['thumbnail'].'"/><br>'.$thumb['album_name'].'<br>'.$thumb['id'].'</a></td>';
}
echo "</tr></table>";
}
?>
The code for getting the passed variable is as follows:
<?php
include("config.php");
$conn = mysqli_connect(DB_DSN,DB_USERNAME,DB_PASSWORD);
$db = mysqli_select_db($conn,dbname);
if (isset($_GET['id'])) {
$album_id = $_GET['id'];
$pic = "SELECT * FROM photos WHERE album_id ='$album_id'";
$picQuery = mysqli_query($conn,$pic);
if (!$picQuery) {
exit();
}
if (mysqli_num_rows($picQuery) == 0) {
echo "Sorry, no Pictures to display for this album";
}
else{
echo "Pictures in the gallery:<br><br>";
while ($result = mysqli_fetch_assoc($picQuery)) {
echo "<img src='".$result['photo_path']."'/>";
}
}
}
?>
Please help as i have spent the last two days trying to get it right.
First, your's code is weak against sql injections:
$album_id = $_GET['id']; // here
$pic = "SELECT * FROM photos WHERE album_id ='$album_id'";
Use either $album_id = intval($_GET['id']) or prepared statements functionality.
Second, add debug lines to your code, like:
<?php
include("config.php");
if (isset($_GET['id'])) {
$album_id = intval($_GET['id']);
var_dump($album_id); // should print actual passed id
$conn = mysqli_connect(DB_DSN,DB_USERNAME,DB_PASSWORD);
var_dump($conn _id); // should print conn resource value
$db = mysqli_select_db($conn, dbname);
var_dump($db); // should print 'true' if db select is ok
$pic = "SELECT * FROM photos WHERE album_id ='$album_id'";
$picQuery = mysqli_query($conn, $pic);
var_dump($picQuery); // should print query resource value
if (!$picQuery) {
exit();
}
if (mysqli_num_rows($picQuery) == 0) {
echo "Sorry, no Pictures to display for this album";
} else {
echo "Pictures in the gallery:<br><br>";
while (($result = mysqli_fetch_assoc($picQuery)) !== false) {
var_dump($result ); // should print fetched assoc array
echo "<img src='".$result['photo_path']."'/>";
}
}
}
Notice $album_id = intval($_GET['id']) and while (($result = mysqli_fetch_assoc($picQuery)) !== false) parts
Then follow link view.php?id=<existing-album-id> and observe debug result. On which step debug output differs from expected - there problem is.

image's table creates differend foreign keys

I have a code which inserts into more 3 tables . what happens is that if I create a new account at the same time I upload images for that account in the images table . The code does it very well but now the problem is it gives each image a unique referenced user_Id yet all images uploaded for that user should be with the same Id from the user table .I am using a relational database where by the user table has a primary key user_id which is referenced to other tables as their foreign key . bellow is my code : ant help will be appreciated .
<?php
#connect to the db
require_once('db.inc.php');
?>
<?php
#code to deal with the picture uploads
#target folder
$target = 'image_uploads/';
if(isset($_FILES['image_name'])===true){
$files = $_FILES['image_name'];
for($x = 0 ; $x < count($files['name']); $x++){
$name = $files['name'][$x] ;
$temp_name = $files['tmp_name'][$x];
#extention filter it takes only the extension want
$allowed ='gif,png,jpg,pdf';
$extension_allowed= explode(',',$allowed );
$file_extention = pathinfo($name, PATHINFO_EXTENSION);
if(array_search($file_extention,$extension_allowed)){
}else {
echo 'We only allow gif, png ,jpg';
exit();
} #extention filter ends here
#check the size of the image
$file_size = $files['size'][$x];
if($file_size > 2097152){
echo 'The file should be lesS than 2MB';
exit();
}
#check the size of the image ends here
#Rename images
$sub = substr(md5(rand()),0,7);
#the above generates char and numbesr
$rand = rand(0,100000);
$rename = $rand.$sub.$name;
#Rename images ends here
$move = move_uploaded_file($temp_name,$target.$rename);
#code to deal with the picture uploads ends here
?>
<?php
$date_created= date('y-m-d h:i:s a');
$username=(isset($_POST['username']))? trim($_POST['username']): '';
$Previllage =(isset($_POST['Previllage']))? trim($_POST['Previllage']): '';
#second tanble values
$title=(isset($_POST['title']))? trim($_POST['title']): '';
$firstname=(isset($_POST['firstname']))? trim($_POST['firstname']): '';
$lastname=(isset($_POST['lastname']))? trim($_POST['lastname']): '';
$client_code=(isset($_POST['client_code']))? trim($_POST['client_code']): '';
$job_approval=(isset($_POST['job_approval']))? trim($_POST['job_approval']): '';
$address=(isset($_POST['address']))? trim($_POST['address']): '';
$cell=(isset($_POST['cell']))? trim($_POST['cell']): '';
$tel=(isset($_POST['tel']))? trim($_POST['tel']): '';
$email=(isset($_POST['email']))? trim($_POST['email']): '';
$company=(isset($_POST['company']))? trim($_POST['company']): '';
$province=(isset($_POST['province']))? trim($_POST['province']): '';
$username= substr(md5(rand()),0,7);
$Pas=substr(md5(rand()),0,4);
$Password =(md5($Pas));
$user =(isset($_POST['$user']))? trim($_POST['$user']): '';
$ip_address = $_SERVER['REMOTE_ADDR'];
try{
$query="INSERT INTO tish_user(username,Password,Previllage,date_created)
VALUES(:username,:Password,:Previllage,:date_created)";
$insert = $con->prepare($query);
$insert->execute(array(
':username'=>$username,
':Password'=>$Password,
':Previllage'=>$Previllage,
':date_created'=>$date_created));
#end of first table
################################################
#You select the first Id and put it in a variable then
$id_last = ("SELECT LAST_INSERT_ID()");
$result =$con->prepare($id_last);
$result->execute();
$last_id = $result->fetchColumn();
############################## Last Id query Ends here
#insert into clientinfo table
$clientinfor="INSERT INTO tish_clientinfo(title,firstname,lastname,user_id)
VALUES(:title,:firstname,:lastname,$last_id)";
$clientinfor_insert = $con->prepare($clientinfor);
$clientinfor_insert->execute(array(
':title'=>$title,
':firstname'=>$firstname,
':lastname'=>$lastname));
#end of clien infor
################################################
$security="INSERT INTO tish_security(ip_address,user_id)
VALUES(:ip_address,$last_id)";
$security_insert = $con->prepare($security);
$security_insert->execute(array(
':ip_address'=>$ip_address));
##########################end of security
############ images
$images ="INSERT INTO tish_images(user_id,image_name,date_registered)
VALUES($last_id,:image_name,:date_registered)";
$images_insert = $con->prepare($images);
$images_insert->execute(array(
':image_name'=>$rename,
':date_registered'=>$date_created));
############# property table##########################################################
/*$property ="INSERT INTO tish_propertyinfo(user_id,date_registered)
VALUES($last_id,:date_registered)";
$property_insert = $con->prepare($images);
$property_insert->execute(array(':date_registered'=>$date_created));
*/}catch(PDOException $e){
echo $e->getMessage();
}
}
}
?>
Is there a auto increment on user_id in the image table? And checknwether $last_id contains anything, I would thinkni is NULL.

How to delete an image using PHP & MySQL?

I was wondering if some one can give me an example on how to delete an image using PHP & MySQL?
The image is stored in a folder name thumbs and another named images and the image name is stored in a mysql database.
Delete the file:
unlink("thumbs/imagename");
unlink("images/imagename");
Remove from database
$sql="DELETE FROM tablename WHERE name='imagename'"
$result=mysql_query($sql);
Assuming name is the the name of the field in the database holding the image name, and imagename is the image's name.
All together in code:
$imgName='sample.jpg';
$dbFieldName='name';
$dbTableName='imageTable';
unlink("thumbs/$imgName");
unlink("images/$imgName");
$sql="DELETE FROM $dbTableName WHERE $dbFieldName='$imgName'";
mysql_query($sql);
try this code :
$img_dir = 'image_directory_name/';
$img_thmb = 'thumbnail_directory_name/';// if you had thumbnails
$image_name = $row['image_name'];//assume that this is the image_name field from your database
//unlink function return bool so you can use it as conditon
if(unlink($img_dir.$image_name) && unlink($img_thmb.$image_name)){
//assume that variable $image_id is queried from the database where your image record your about to delete is...
$sql = "DELETE FROM table WHERE image_id = '".$image_id."'";
$qry = mysql_query($sql);
}else{
echo 'ERROR: unable to delete image file!';
}
Are you looking for actual code or just the idea behind it?
You'll need to query the db to find out the name of the file being deleted and then simply use unlink to delete the file in question.
so here's some quick code to get you started
<?php
$thumb_dir = "path/to/thumbs/";
$img_dir = "path/to/images/";
/* query your db to get the desired image
I'm guessing you're using a form to delete the image?
if so use something like $image = $_POST['your_variable'] to get the image
and query your db */
// once you confirm that the file exists in the db check to see if the image
// is actually on the server
if(file_exists($thumb_dir . $image . '.jpg')){
if (unlink($thumb_dir . $image . '.jpg') && unlink($img_dir . $image . '.jpg'))
//it's better to use the ID rather than the name of the file to delete it from db
mysql_query("DELETE FROM table WHERE name='".$image."'") or die(mysql_error());
}
?>
if(!empty($_GET['pid']) && $_GET['act']=="del")
{
$_sql = "SELECT * FROM mservices WHERE pro_id=".$_GET['pid'];
$rs = $_CONN->Execute($_sql);
if ($rs->EOF) {
$_MSG[] = "";
$error = 1;
}
if ($rs)
$rs->close();
if (!$error) {
$_Image_to_delete = "select pro_img from mservices where pro_id=".$_GET['pid'];
$trial=$_CONN->Execute($_Image_to_delete);
$img = trim(substr($trial,7));
unlink($_DIR['inc']['product_image'].$img);
$_sql = "delete from mservices where pro_id=".$_GET['pid'];
$_CONN->Execute($_sql);
header("Location: ".$_DIR['site']['adminurl']."mservices".$atend."suc".$_DELIM."3".$baratend);
exit();
}
}
$_sql = "SELECT * FROM mservices WHERE pro_id=".$_GET['pid'];
$rs = $_CONN->Execute($_sql);
if ($rs->EOF) {
$_MSG[] = "";
$error = 1;
}
if ($rs)
$rs->close();
if (!$error) {
$_Image_to_delete = "select pro_img from mservices where pro_id=".$_GET['pid'];
$trial=$_CONN->Execute($_Image_to_delete);
$img = trim(substr($trial,7));
unlink($_DIR['inc']['product_image'].$img);
$_sql = "delete from mservices where pro_id=".$_GET['pid'];
$_CONN->Execute($_sql);
header("Location: ".

Categories