image's table creates differend foreign keys - php

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.

Related

why the picture gone after do the update data in PHP

lets say i have 2 column in my inventory data called category and image_name in my php and database.
image_name are coming from this (basically in my database, image_name contain the link of the uploaded image) :
<?php
if ($_SERVER["REQUEST_METHOD"] == "POST") {
$file = $_FILES['uploadgambar'];
$fileName = $_FILES['uploadgambar']['name'];
$fileTmpName = $_FILES['uploadgambar']['tmp_name'];
$fileSize = $_FILES['uploadgambar']['size'];
$fileError = $_FILES['uploadgambar']['error'];
$fileType = $_FILES['uploadgambar']['type'];
$fileExt = explode('.', $fileName);
$fileActualExt = strtolower(end($fileExt));
$allowed = array('jpg', 'jpeg', 'png');
if (in_array($fileActualExt, $allowed)) {
if ($fileError === 0) {
if ($fileSize < 5000000) {
$fileNameNew = uniqid('', true) . "." . $fileActualExt;
$fileDestination = 'uploads/' . $fileNameNew;
move_uploaded_file($fileTmpName, $fileDestination);
// header("Location: index.php?uploadsuccess");
} else {
echo "File anda terlalu besar (maximal 1gb)";
}
} else {
echo "Terdapat error dalam mengupload file";
}
} else {
echo "Anda tidak bisa upload file ini karena tidak berbentuk JPG/JPEG/PNG";
}
i build some code for update feature for category and image_name column like this
$kategori = mysqli_real_escape_string($conn, $_POST["kategori"]);
$image_name = mysqli_real_escape_string($conn, $fileDestination);
and here's for the update
$sql1 = "update $tabeldatabase set kategori='$kategori', image_name = '$image_name' where kode = '$kode';
$updatean = mysqli_query($conn, $sql1);
echo "<script type='text/javascript'> alert('Berhasil, Data barang telah diupdate!'); </script>";
echo "<script type='text/javascript'>window.location = '$forwardpage';</script>";
but the problem is, when i update the image its run, but when i update kategori, idk why my picture gone and when i look at the database, column image_name has removed for that id and cause the image gone.
my expected result is, just like update feature, if i update the category, then the image_name wont missing.
I am writing your answer, but maybe it needs some editions. so add some comments if the ways not fix the problem.
one of the reasons maybe due to updating the row of database even if the file name is empty. so you must check the file name before update the database table record.
In this code, whenever you don't have upload file, so $fileDestination will be empty, so the cell of table will be empty and image address will gone!
For that problem, you could change the query:
$sql1 = "update $tabeldatabase set kategori='$kategori', image_name = '$image_name' where kode = '$kode';
to something like this:
if ($image_name) {
$sql1 = "update $tabeldatabase set kategori='$kategori', image_name = '$image_name' where kode = '$kode';
} else {
$sql1 = "update $tabeldatabase set kategori='$kategori' where kode = '$kode';
}
Apart from this I recommend you to change this row:
$sql1 = "update $tabeldatabase set kategori='$kategori', image_name = '$image_name' where kode = '$kode';
to a fixed table name like this:
$sql1 = "update my_static_table_name set kategori='$kategori', image_name = '$image_name' where kode = '$kode';
so you can easily debug the problem.

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 upload and insert multiple images in PHP and mysql database

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

Form submit PHP code broken only in Wordpress

I have a simple form for submitting some data into the MySQL DB. On local machine works just fine, but inside a Wordpress page template doesn't work anymore, without getting me any error. The form is inside a page "sitename.com/upload" and i get redirected after submit to the same page (as shown in the link bar), but with 404 page content. I tried without get_header();and get_footer();tags because I thought it may conflict with some variables from wp, but I got the same result.
Here is the code:
<?php function renderForm($name, $price, $error)
{
// if there are any errors, display them
if ($error != '')
{
echo '<div style="padding:4px; border:1px solid red; color:red;">'.$error.'</div>';
}
?>
***** LONG HTML FORM IS HERE *****
<?php
}
// connect to the database
include('connect-db.php');
// check if the form has been submitted. If it has, start to process the form and save it to the database
if (isset($_POST['submit']))
{
// get form data, making sure it is valid
$name = mysqli_real_escape_string($connection, htmlspecialchars($_POST['name']));
$price = mysqli_real_escape_string($connection, htmlspecialchars($_POST['price']));
$shortdesc = mysqli_real_escape_string($connection, htmlspecialchars($_POST['shortdesc']));
$longdesc = mysqli_real_escape_string($connection, htmlspecialchars($_POST['longdesc']));
$current_version = mysqli_real_escape_string($connection, htmlspecialchars($_POST['current-version']));
$content_rating = $_POST['contentrating'];
if(isset($_POST['category'])) {
$category = implode(",", $_POST['category']);
} else {
$category = "";
}
if(isset($_POST['platform'])) {
$platform = implode(",", $_POST['platform']);
} else {
$platform = "";
}
if(isset($_POST['devices'])) {
$devices = implode(",", $_POST['devices']);
} else {
$devices = "";
}
if(isset($_POST['gamemodes'])) {
$gamemodes = implode(",", $_POST['gamemodes']);
} else {
$gamemodes = "";
}
//FILE UPLOAD
$images = array();
if(isset($_FILES['files'])){
$errors= array();
foreach($_FILES['files']['tmp_name'] as $key => $tmp_name ){
$file_name =$_FILES['files']['name'][$key];
$file_size =$_FILES['files']['size'][$key];
$file_tmp =$_FILES['files']['tmp_name'][$key];
$file_type=$_FILES['files']['type'][$key];
if($file_size > 2097152){
$errors[]='File size must be less than 2 MB';
}
$desired_dir="uploads/images";
if(empty($errors)==true){
if(is_dir($desired_dir)==false){
mkdir("$desired_dir", 0700); // Create directory if it does not exist
}
if(is_dir("$desired_dir/".$file_name)==true){
move_uploaded_file($file_tmp,"uploads/images/".$file_name);
}else{ //rename the file if another one exist
$file_name = time()."-".$file_name;
$new_dir="uploads/images/".$file_name;
rename($file_tmp,$new_dir) ;
}
$images[] = $file_name;
}else{
print_r($errors);
}
}
if(empty($error)){
$imglinks = implode(" | ", $images);
}
}
//FILE UPLOAD END
// check to make sure both fields are entered
if ($name == '' || $price == '')
{
// generate error message
$error = 'ERROR: Please fill in all required fields!';
// if either field is blank, display the form again
renderForm($name, $price, $error);
}
else
{
$sql = "INSERT INTO vr_submitted_apps ". "(name, price, shortdesc, longdesc, crtvers, rating, category, platform, devices, gamemodes, images, dtime) ". "VALUES('$name','$price','$shortdesc','$longdesc','$current_version','$content_rating','$category','$platform','$devices','$gamemodes', '$imglinks', NOW())";
// save the data to the database
mysqli_query( $connection, $sql )
or die(mysql_error());
$itemId = mysqli_insert_id($connection);
setcookie("last-inserted-id", $itemId, time() + (86400 * 3), "/"); // 86400 = 1 day
// once saved, redirect back to the view page
header("Location: uploader.html");
}
}
else
// if the form hasn't been submitted, display the form
{
renderForm('','','');
}
Problem solved: Wordpress has something important internal reserved for "name" parameter.

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