How to update mysqli field if the value is not empty - php

I am trying to update a specific value from my table getting them as row from a table let's say the name but the problem is the image, cause i can't pass a value to an input field type = file
I need to update the value in the database only if there is a value to change if not don't change the value that already is there.
My query looks like this and i would like to know what i can change to update image value only if there is a value
//image upload + validation
$file = $_FILES['image'];
$file_name = $_FILES['image']['name'];//file name
var_dump($file_name);
$file_location = $_FILES['image']['tmp_name']; //temporary location
$file_size = $_FILES['image']['size'];// size
$file_error = $_FILES['image']['error'];// error 0 if no error or 1 if there is an error
$temp_extension = explode('.',$file_name);//explode from . file extension, we have file name and extension
$file_extension = strtolower(end($temp_extension)); // extension name (end return the last element of the array)
$allowed_extensions = array('jpg', 'jpeg', 'png', 'pdf');
if (empty($file_name)) {
if (in_array($file_extension, $allowed_extensions)) {
if ($file_error === 0) {
if ($file_size < 15728640) { //15728640b(bytes binary) 15mb mediumblob
$new_file_name = uniqid('',true).".".$file_extension;
// var_dump($new_file_name);
$file_destination = dirname(__FILE__, 2)."/images/".$new_file_name;
move_uploaded_file($file_location, $file_destination);
}else {
echo "Sorry your file size it's too big!";
}
}else {
echo "Sorry, there was an error, try again";
}
}else {
echo "Sorry, your file type is not accepted";
}
}
if(is_array($row)) {
$sql = "UPDATE `accommodation` SET `name` = '{$_POST['name']}', `image` = '$new_file_name', `description` = '{$_POST['description']}', `adress` = '{$_POST['adress']}', `link` = '{$_POST['link']}' WHERE `id` = '{$_POST['id']}'";
mysqli_query(get_connection(), $sql);
var_dump($sql);
// header("Location: admin.php?page=accommodation_list");
}else{
$conn = get_connection();
$sql = "INSERT INTO `accommodation` (`name`, `image`, `description`, `adress`, `link`) VALUES ('{$_POST['name']}', '$new_file_name', '{$_POST['description']}', '{$_POST['adress']}', '{$_POST['link']}')";
mysqli_query($conn, $sql);
$accommodation_id = mysqli_insert_id($conn);
header("Location: admin.php?page=room_add_edit");
}//end if else
This is the query that i need to change but i don't know how....
$sql = "UPDATE `accommodation` SET `name` = '{$_POST['name']}', `image` = '$new_file_name', `description` = '{$_POST['description']}', `adress` = '{$_POST['adress']}', `link` = '{$_POST['link']}' WHERE `id` = '{$_POST['id']}'";
I am aware of SQL injection but first i need this query to work then i will work on SQL injection, and i typed address as adress and i have to change that too.
I have changed the code to this but i don't know if it's a good way to do it
//image upload + validation
$file = $_FILES['image'];
$file_name = $_FILES['image']['name'];//file name
var_dump($file_name);
$file_location = $_FILES['image']['tmp_name']; //temporary location
$file_size = $_FILES['image']['size'];// size
$file_error = $_FILES['image']['error'];// error 0 if no error or 1 if there is an error
$temp_extension = explode('.',$file_name);//explode from . file extension, we have file name and extension
$file_extension = strtolower(end($temp_extension)); // extension name (end return the last element of the array)
$allowed_extensions = array('jpg', 'jpeg', 'png', 'pdf');
if (!empty($file_name)) {
if (in_array($file_extension, $allowed_extensions)) {
if ($file_error === 0) {
if ($file_size < 15728640) { //15728640b(bytes binary) 15mb mediumblob
$new_file_name = uniqid('',true).".".$file_extension;
// var_dump($new_file_name);
$file_destination = dirname(__FILE__, 2)."/images/".$new_file_name;
move_uploaded_file($file_location, $file_destination);
$text1 = "`image` = '$new_file_name',";
}else {
echo "Sorry your file size it's too big!";
}
}else {
echo "Sorry, there was an error, try again";
}
}else {
echo "Sorry, your file type is not accepted";
}
}else {
$text1 = "";
}
if(is_array($row)) {
$sql = "UPDATE `accommodation` SET `name` = '{$_POST['name']}', $text1 `description` = '{$_POST['description']}', `adress` = '{$_POST['adress']}', `link` = '{$_POST['link']}' WHERE `id` = '{$_POST['id']}'";
mysqli_query(get_connection(), $sql);
var_dump($sql);
// header("Location: admin.php?page=accommodation_list");
}

you can simply check the file uploaded or not using a third variable. If file uploaded than save new file name otherwise save the old file name. So you will not lose your file on update. I am assuming you are getting whole row data in $row so check below code
$is_file_uploaded = 0;
if (empty($file_name)) {
if (in_array($file_extension, $allowed_extensions)) {
if ($file_error === 0) {
if ($file_size < 15728640) { //15728640b(bytes binary) 15mb mediumblob
$new_file_name = uniqid('',true).".".$file_extension;
// var_dump($new_file_name);
$file_destination = dirname(__FILE__, 2)."/images/".$new_file_name;
move_uploaded_file($file_location, $file_destination);
$is_file_uploaded = 1;
}else {
echo "Sorry your file size it's too big!";
}
}else {
echo "Sorry, there was an error, try again";
}
}else {
echo "Sorry, your file type is not accepted";
}
if(is_array($row)) {
$new_file_name = ($is_file_uploaded == 1) ? $new_file_name : $row['image'];
//your code
}
}

You can try this:
$new_file_name = "";
if (!empty($file_name)) {
if (in_array($file_extension, $allowed_extensions)) {
if ($file_error === 0) {
if ($file_size < 15728640) { //15728640b(bytes binary) 15mb mediumblob
$new_file_name = uniqid('',true).".".$file_extension;
// var_dump($new_file_name);
$file_destination = dirname(__FILE__, 2)."/images/".$new_file_name;
move_uploaded_file($file_location, $file_destination);
}else {
echo "Sorry your file size it's too big!";
}
}else {
echo "Sorry, there was an error, try again";
}
}else {
echo "Sorry, your file type is not accepted";
}
}
if(is_array($row)) {
if($new_file_name != ""){
$sql = "UPDATE `accommodation` SET `name` = '{$_POST['name']}', `image` = '$new_file_name', `description` = '{$_POST['description']}', `adress` = '{$_POST['adress']}', `link` = '{$_POST['link']}' WHERE `id` = '{$_POST['id']}'";
}else{
$sql = "UPDATE `accommodation` SET `name` = '{$_POST['name']}', `description` = '{$_POST['description']}', `adress` = '{$_POST['adress']}', `link` = '{$_POST['link']}' WHERE `id` = '{$_POST['id']}'";
}
mysqli_query(get_connection(), $sql);
var_dump($sql);
// header("Location: admin.php?page=accommodation_list");
}

Related

How to save an image to the database with a path file

I am trying to save a picture into my database along with the path file. But what it does now is incorrect. It only saves the image into the database and not the entire image path. What's wrong?
I do the exact same thing with this code in another project and can't wrap my head around the problem here.
$userPic = '';
$date_time = date('Y-m-d_H-i-s');
if(!empty($userLoggedIn)) {
if (isset($_FILES['fileToUpload'])) {
$errors = array();
$file_name = $_FILES['fileToUpload']['name'];
$file_size = $_FILES['fileToUpload']['size'];
$width = 1500;
$height = 1500;
$file_tmp = $_FILES['fileToUpload']['tmp_name'];
$file_type = $_FILES['fileToUpload']['type'];
$tmp = explode('.', $_FILES['fileToUpload']['name']);
$file_ext = strtolower (end ($tmp));
$extensions = array("jpeg", "jpg", "png", "gif");
if(in_array($file_ext, $extensions) === false) {
$errors[] = "extension not allowed. Please choose a JPEG or PNG file.";
}
if ($file_size > 8097152) {
$errors[] = 'File size must be 2 MB';
}
if ($width > 1500 || $height > 1500) {
echo"File is to large";
}
if(!$errors) {
$userPic = md5($_FILES["fileToUpload"]["name"]) . $date_time . " " . $file_name;
move_uploaded_file($file_tmp, "assets/images/profile_pics/" . $userPic);
$stmt = $con->prepare("UPDATE users SET profile_pic = ? WHERE username = ?");
$stmt->bind_param('ss', $userPic, $username);
$stmt->execute();
$stmt->close();
}
}
}
else {
echo "Invalid Username";
}
You can assign another variable that contains both the path and the variable for the image you used, and then use that variable in your query:
$file_path = "assets/images/profile_pics/".$userPic;
Your code:
if(!$errors) {
$userPic = md5($_FILES["fileToUpload"]["name"]) . $date_time . " " . $file_name;
move_uploaded_file($file_tmp,"assets/images/profile_pics/" . $userPic);
$imag_path = "assets/images/profile_pics/" . $userPic;
$stmt = $con->prepare("UPDATE users SET profile_pic = ? WHERE username = ?");
$stmt->bind_param('ss', $imag_path, $username);
$stmt->execute();
$stmt->close();
}
Try this:
You save only the new image name, not path.

Update image with information in php

I've been looking for a code to update my image from the database from youtube and here in stackoverflow. But I cant seem to make it work. The image can get updated but the title and the body cannot be edited. please help.
im usig it with php and phpmyadmin
this is the code i've been trying to make the update:
if (isset($_POST['update'])) {
$id = $_POST['editid'];
$edtitle = $_POST['edittitle'];
$edbody = $_POST['editmyTextarea'];
$file = $_FILES['editpgupload'];
$filename = $file['name'];
$fileTmp = $file['tmp_name'];
$filesize = $file['size'];
$fileerror = $file['error'];
$filetype = $file['type'];
$fileExt = explode('.', $filename);
$fileActExt = strtolower(end($fileExt));
$allowed = array('jpg', 'jpeg', 'png');
if (in_array($fileActExt, $allowed)) {
if ($fileerror === 0) {
if ($filesize < 1000000) {
$filenamenew = uniqid('', true).".".$fileActExt;
$fileds = '../../../image/upload/'.$filenamenew;
move_uploaded_file($fileTmp, $fileds);
$sql = "UPDATE patients_guide SET pg_title = '$edtitle', pg_body = '$edbody', pg_image = '$filenamenew' WHERE pg_id = '$id'";
mysqli_query($conn, $sql);
header("Location: ../index.php?update=success");
}else{
// echo "your image is too large";
header("Location: ../index.php?error=imagetoolarge");
}
}else{
// echo "There was an error uploading your file";
header("Location: ../index.php?error=errorupload");
}
}else{
// echo "You can not upload this file";
header("Location: ../index.php?error=cannotupload");
}
}
it only updates the image but the title and the body stay the same. it cannot be edited. this should be able to update the title, body and the image.
patients_guide structure
CREATE TABLE `patients_guide` (
`pg_id` int(11) NOT NULL AUTO_INCREMENT,
`pg_title` varchar(100) NOT NULL,
`pg_body` text NOT NULL,
`pg_image` varchar(100) NOT NULL,
PRIMARY KEY (`pg_id`)
) ENGINE=InnoDB AUTO_INCREMENT=12 DEFAULT CHARSET=utf
I got it.
For someone that has the same problem as me here is the code:
if (isset($_POST['update'])) {
$id = $_POST['editid'];
$edtitle = $_POST['edittitle'];
$edbody = $_POST['editmyTextarea'];
$file = $_FILES['editpgupload'];
$filename = $file['name'];
$fileTmp = $file['tmp_name'];
$filesize = $file['size'];
$fileerror = $file['error'];
$filetype = $file['type'];
//remove old image
unlink('../../../image/upload/'.$row['pg_image']);
$fileExt = explode('.', $filename);
$fileActExt = strtolower(end($fileExt));
$allowed = array('jpg', 'jpeg', 'png');
if (in_array($fileActExt, $allowed)) {
if ($fileerror === 0) {
if ($filesize < 1000000) {
$filenamenew = uniqid('', true).".".$fileActExt;
$fileds = '../../../image/upload/'.$filenamenew;
move_uploaded_file($fileTmp, $fileds);
$sql = "UPDATE patients_guide SET pg_title = '$edtitle', pg_body = '$edbody', pg_image = '$filenamenew' WHERE pg_id = '$id'";
mysqli_query($conn, $sql);
header("Location: ../index.php?update=success");
}else{
// echo "your image is too large";
header("Location: ../index.php?error=imagetoolarge");
}
}else{
// echo "There was an error uploading your file";
header("Location: ../index.php?error=errorupload");
}
}else{
$sql = "UPDATE patients_guide SET pg_title = '$edtitle', pg_body = '$edbody' WHERE pg_id = '$id'";
mysqli_query($conn, $sql);
header("Location: ../index.php?update=success");
}
}

oci_excute error when try to upload file php

This code should upload a blob file image to oracle database. While I try to use the following code, the variable $objExecute produces an error!
Please help to fix this.
$error= $_FILES['Image_assigned']['error'];
$objConnect = oci_connect("jab","jabee","j-windows7/XE");
$lob = oci_new_descriptor($objConnect, OCI_D_LOB);
$strSQL ="insert into SS_USERS_PIC (SYSUID,PICTURE) values (F_SS_GET_AUTO_ID('SYSUID','PICTURE') , EMPTY_BLOB()) RETURNING ImageFile INTO :BLOBDATA " .")";
// $strSQL='insert into mybtab (blobid, blobdata) values (:myblobid, EMPTY_BLOB()) returning blobdata into :blobdata';
$objParse = oci_parse($objConnect, $strSQL);
oci_bind_by_name($objParse, ':BLOBDATA', $lob, -1, OCI_B_BLOB);
$objExecute = oci_execute($objParse, OCI_DEFAULT);
$lob->savefile($_FILES['Image_assigned']['tmp_name']);
$errorCode= $_FILES['Image_assigned']['error'];
if ($objExecute)
{
oci_commit($objConnect);
echo "Copy/Upload Complete<br>";
}
else
{
oci_rollback($objConnect);
trigger_error(htmlentities($e['message']), E_USER_ERROR);
echo "Copy/Upload is not Complete";
}
function upload($operation){
if(!empty($_FILES['Image_assigned']['name']) && !($_FILES['Image_assigned']['error']))
{
$uploadedFile = '';
if(!empty($_FILES["Image_assigned"]["type"]))
{
$fileName = time().'_'.$_FILES['Image_assigned']['name'];
$valid_extensions = array("jpeg", "jpg", "png");
$temporary = explode(".", $_FILES["Image_assigned"]["name"]);
$file_extension = end($temporary);
$blobdata = file_get_contents($_FILES['Image_assigned']['tmp_name']);
if((($_FILES["hard_file"]["type"] == "image/png") || ($_FILES["Image_assigned"]["type"] == "image/jpg") || ($_FILES["Image_assigned"]["type"] == "image/jpeg")) && in_array($file_extension, $valid_extensions))
{
$sourcePath = $_FILES['Image_assigned']['tmp_name'];
$targetPath = "uploads/".$fileName;
}
}
$objConnect = oci_connect("[username]","[password]","[hostname]/[instnce_name]");
$lob = oci_new_descriptor($objConnect, OCI_D_LOB);
if ($operation=='ADD'){
$strSQL ="insert into [TableName] (PICTURE) values ( EMPTY_BLOB()) RETURNING PICTURE INTO :BLOBDATA ";
$objParse = oci_parse($objConnect, $strSQL);
}
// *************************************
oci_bind_by_name($objParse, ':BLOBDATA', $lob, -1, OCI_B_BLOB);
try
{
$objExecute = oci_execute($objParse, OCI_DEFAULT);
$lob->savefile($_FILES['Image_assigned']['tmp_name']);
}
catch (Exception $e) {
$err = $e->getMessage();
}
if($objExecute)
{
oci_commit($objConnect);
echo "Copy/Upload Complete<br>";
}
else
{
oci_rollback($objConnect);
trigger_error(htmlentities($e['message']), E_USER_ERROR);
echo "Copy/Upload is not Complete";
}
oci_free_descriptor($lob);
oci_free_statement($objParse);
oci_close($objConnect);
}
}

PHP- file uploading working on localhost but not in server (linux)

Upload file not working on server but it is working on localhost. File upload permission is ON, but even getting error. I tried all the solution over internet.
Here is my code.
if($submit == "UPLOAD PROFILE PICTURE") {
$user = $_COOKIE['userId'];
$file_name = $_FILES['userPic']['name'];
$file_size =$_FILES['userPic']['size'];
$file_tmp =$_FILES['userPic']['tmp_name'];
$file_type=$_FILES['userPic']['type'];
$tmp = explode('.', $file_name);
$file_ext = end($tmp);
$expensions= array("jpeg","jpg","png");
$nameToStore = $user.".".$file_ext;
chmod("images/users-dp/$nameToStore",0777);
if(in_array($file_ext,$expensions)=== true){
if($file_size < 2097152){
if(move_uploaded_file($file_tmp,"images/users-dp/".$nameToStore)) {
$queryFoCheck = "SELECT * FROM profilepic WHERE user = '$user'";
$resultFoCheck = $connection -> query($queryFoCheck);
$countFoCheck = mysqli_num_rows($resultFoCheck);
if($countFoCheck>=1) {
$query = "UPDATE profilepic SET piclink = '$nameToStore' WHERE user = '$user'";
$result = $connection -> query($query);
} else {
$query = "INSERT INTO profilepic VALUES ('$user', '$nameToStore') ";
$result = $connection -> query($query);
}
header('Location: profile.php?s'); //successsfully updated
} else {
header('Location: profile.php?e=1'); //Cant update
}
} else {
header('Location: profile.php?e=2'); //Cant update
}
} else {
header('Location: profile.php?e=3'); //Cant update
}
}

Optional file upload fields

I am trying to make my two file uploads optional when inserting data into mySQL db, and uploading the files to my server. When I uploading both files to a new entry, the upload is successful. If I don't upload 1 or both files, I receive an error. Thank you so much for your help.
<?php require_once($_SERVER['DOCUMENT_ROOT']."/includes/session.php");?>
<?php require_once($_SERVER['DOCUMENT_ROOT']."/includes/db_connection.php");?>
<?php
session_start();
if($_SESSION["login_user"] != true) {
echo("Access denied!");
exit();
}
?>
<?php require_once($_SERVER['DOCUMENT_ROOT']."/includes/functions.php");?>
<?php require_once($_SERVER['DOCUMENT_ROOT']."/includes/validation_functions.php");?>
<?php
if (isset($_POST['submit'])) {
// Process the form
$visible = mysqli_prep($_POST["visible"]);
$homepage = mysqli_prep($_POST["homepage"]);
$type = mysqli_prep($_POST["type"]);
$publication_name = mysqli_prep($_POST["publication_name"]);
$publication_url = mysqli_prep($_POST["publication_url"]);
$month = mysqli_prep($_POST["month"]);
$date = mysqli_prep($_POST["date"]);
$year = mysqli_prep($_POST["year"]);
$title = mysqli_prep($_POST["title"]);
$author = mysqli_prep($_POST["author"]);
$summary = mysqli_prep($_POST["summary"]);
$full_text = mysqli_prep($_POST["full_text"]);
$tag_1 = mysqli_prep($_POST["tag_1"]);
$tag_2 = mysqli_prep($_POST["tag_2"]);
$tag_3 = mysqli_prep($_POST["tag_3"]);
$tag_4 = mysqli_prep($_POST["tag_4"]);
$tag_5 = mysqli_prep($_POST["tag_5"]);
$tag_6 = mysqli_prep($_POST["tag_6"]);
$tag_7 = mysqli_prep($_POST["tag_7"]);
$image = rand(1000,100000)."-".$_FILES['image']['name'];
$image_loc = $_FILES['image']['tmp_name'];
$image_size = $_FILES['image']['size'];
$image_type = $_FILES['image']['type'];
$image_folder="images/";
$file = rand(1000,100000)."-".$_FILES['file']['name'];
$file_loc = $_FILES['file']['tmp_name'];
$file_size = $_FILES['file']['size'];
$file_type = $_FILES['file']['type'];
$file_folder="files/";
$image_new_size = $image_size/1024;
$file_new_size = $file_size/1024;
$new_image_name = strtolower($image);
$new_file_name = strtolower($file);
$final_image=str_replace(' ','-',$new_image_name);
$final_file=str_replace(' ','-',$new_file_name);
if(move_uploaded_file($image_loc,$image_folder.$final_image))
if(move_uploaded_file($file_loc,$file_folder.$final_file))
$query = "INSERT INTO `news` (";
$query .= "visible, homepage, type, publication_name, publication_url, month, date, year, title, author, summary, full_text, tag_1, tag_2, tag_3, tag_4, tag_5, tag_6, tag_7, image, image_type, image_size, file, file_type, file_size ";
$query .= ") VALUES (";
$query .= " '{$visible}', '{$homepage}', '{$type}', '{$publication_name}', '{$publication_url}', '{$month}', '{$date}', '{$year}', '{$title}', '{$author}', '{$summary}', '{$full_text}', '{$tag_1}', '{$tag_2}', '{$tag_3}', '{$tag_4}', '{$tag_5}', '{$tag_6}', '{$tag_7}', '{$final_image}','{$image_type}','{$image_new_size}', '{$final_file}','{$file_type}','{$file_new_size}'";
$query .= ")";
$result = mysqli_query($connection, $query);
if ($result) {
// Success
$_SESSION["message"] = "Item created.";
redirect_to("manage_content.php");
} else {
// Failure
//$_SESSION["message"] = "Item creation failed.";
//redirect_to("new_news.php");
echo "Error: " . $query . "<br>" . $result->error;
}
} else {
// This is probably a GET request
redirect_to("new_news.php");
}
?>
<?php
if (isset($connection)) { mysqli_close($connection); }
?>
you can use this and hence get rid of your error.Hope this helps you.
$final_image = $image_type = $image_new_size = $final_file = $file_type = $file_new_size = "";
if($_FILES) {
$image = rand(1000,100000)."-".$_FILES['image']['name'];
$image_loc = $_FILES['image']['tmp_name'];
$image_size = $_FILES['image']['size'];
$image_type = $_FILES['image']['type'];
$image_folder="images/";
$file = rand(1000,100000)."-".$_FILES['file']['name'];
$file_loc = $_FILES['file']['tmp_name'];
$file_size = $_FILES['file']['size'];
$file_type = $_FILES['file']['type'];
$file_folder="files/";
$image_new_size = $image_size/1024;
$file_new_size = $file_size/1024;
$new_image_name = strtolower($image);
$new_file_name = strtolower($file);
$final_image=str_replace(' ','-',$new_image_name);
$final_file=str_replace(' ','-',$new_file_name);
if(move_uploaded_file($image_loc,$image_folder.$final_image))
if(move_uploaded_file($file_loc,$file_folder.$final_file))
}

Categories