How do I add images to my PHP blog? - php

I have made a blog for my website with PHP and mysql database, where I can add blog posts from an admin site (www.website.com/admin) and display them on my website (www.website.com). It's working fine, but I want to add pictures too.
This is my code for adding:
if (isset($_POST['submit'])) {
$blogtitle = htmlentities($_POST['blogtitle'], ENT_QUOTES);
$blogdate = htmlentities($_POST['blogdate'], ENT_QUOTES);
$blogdesc = htmlentities($_POST['blogdesc'], ENT_QUOTES);
// check that firstname and lastname are both not empty
if ($blogtitle == '' || $blogdesc == '') {
$error = 'Please fill in all required fields';
renderForm($blogtitle, $blogdesc, $error);
} else {
// insert the new record into the database
if ($stmt = $mysqli->prepare("INSERT blog_posts (blogtitle, blogdate, blogdesc) VALUES (?, ?, ?)")) {
$stmt->bind_param("sss", $blogtitle, $blogdate, $blogdesc);
$stmt->execute();
$stmt->close();
} else {
echo "ERROR: Could not prepare SQL statement.";
}
header("Location: website.php");
}
} else {
renderForm();
}
}
// close the mysqli connection
$mysqli->close();
And my code for display the blog posts
/.../
while ($row = $result->fetch_object()) {
echo "<div>";
echo "<td>" . $row->blogtitle . "</td>";
echo "<td>" . $row->blogdate . "</td>";
echo "<td>" . $row->blogdesc . "</td>";
echo "</div>";
}
I know how to make an upload.php, but is it easier to upload to mysql? I dont know how to get the image shown in the right blogpost after uploading.
Best regards,
Tobias Dybdahl

You can upload the file to the server and then store the filename in your database, for example a column named "blogimg".
Then in your code for displaying blog posts you can add this line to show the image:
echo "<td><img src='" . $row->blogimg . "' /></td>";

you need to upload images to a directory and save images name in a database
after that right the url of the image in img tag and get the image name from the database
your html form
<form action="upload.php" method="post" enctype="multipart/form-data">
Select image to upload:
<input type="file" name="fileToUpload" id="fileToUpload">
<input type="submit" value="Upload Image" name="submit">
</form>
your php code
<?php
$target_dir = "uploads/";
$target_file = $target_dir . basename($_FILES["fileToUpload"]["name"]);
$uploadOk = 1;
$imageFileType = pathinfo($target_file,PATHINFO_EXTENSION);
// Check if image file is a actual image or fake image
if(isset($_POST["submit"])) {
$check = getimagesize($_FILES["fileToUpload"]["tmp_name"]);
if($check !== false) {
echo "File is an image - " . $check["mime"] . ".";
$uploadOk = 1;
} else {
echo "File is not an image.";
$uploadOk = 0;
}
}
?>

Related

Unable to save text to mysql database and also how to comment quote reply

I have this code where i write comment in a textarea field and select a picture and sumbit to mysqli database through php, but the problem im having is when i only select a picture to upload or when i write a comment/texts in the textarea and select a picture to upload it works but then when i only write comment/texts in the textarea field and submit it doesn't work.
And also i want to create a comment reply "quote" , like to click reply on a comment then quote and reply the comment.
// My compose form
<form method="post" action="process.php" enctype='multipart/form-data'>
<textarea class="text-area" cols="75" name="comment" type="text" rows="5" placeholder="write message"></textarea><br>
<input type='file' style="width:257px" name='fileToUpload' ><br>
<input class="submitButton" type='submit' value='Send'>
</form>
// My process.php code
<?php
// start username session
session_start();
//connect to database
require_once ("dtb.php");
$commentSenderName = $_SESSION['username'];
$date = date('Y-m-d H:i:s');
$comment = isset($_POST['comment']) ? htmlspecialchars($_POST['comment']) : "";
//Directory where to upload file
$name = $_FILES['fileToUpload']['name'];
$target_dir = "upload/";
$target_file = $target_dir . basename($_FILES["fileToUpload"]["name"]);
//Select file type
$imageFileType = strtolower(pathinfo($target_file,PATHINFO_EXTENSION));
//Valid file extensions
$extensions_arr = array("jpg","jpeg","png","gif","NULL");
//Check extension
if( in_array($imageFileType,$extensions_arr) ){
//Upload file
move_uploaded_file($_FILES['fileToUpload']['tmp_name'],$target_dir.$name);
//Insert data into tables
$sql = "INSERT INTO tblcomment(comment,comment_sender_name,date,image) VALUES ('". $comment . "','" . $commentSenderName . "','" . $date . "','".$name."')";
$result = mysqli_query($conn, $sql);
if (! $result) {
$result = mysqli_error($conn);
}
echo "<p style='padding-left:22px;padding-top:10px;font-family:verdana;font-size:20px'> Post entered... </p>";
header("Refresh: 3; url=mysite.com");
} else {
echo "Error: " . $sql . "<br>" . mysqli_error($conn);
}
mysqli_close($conn);
?>
// This is the code that fetches and display data from mysql database
$sql = "SELECT comment_sender_name,date,comment,image FROM tblcomment";
$result = mysqli_query($conn, $sql);
if (mysqli_num_rows($result) > 0) {
//output data of each row
while($row = mysqli_fetch_assoc($result)) {
$name = $row['comment_sender_name'];
$time = $row['date'];
$msg = $row['comment'];
$img = $row['image'];
$now = array("<span><b style='font-size:25px'> $name </b></span>","<span style='font-size:14px;color:#474747;padding-left:40px;'><i>$time</i></span>");
$message = "<p style='color:#232323;font-size:20px;font-weight:bold'> $msg </p>";
$image_src = "<a href='#'><img src='upload/$img' style='width:550px;height:320px;border-radius:5px'></img></a>";
echo '<table border="0" style="padding-left:25px;box-sizing;height:450px;width:400px;">
<tr>
<td>' .$now[0] .$now[1] .$message .$image_src. "<br/><br/><br/><br/>". '</td>
</tr>';
}
} else {
echo "<p style='padding-left:22px'> 0 results </p>";
}
//Free result set
mysqli_free_result($result);
?>
Im not getting any kind of error.
Aside from my comment above with the many, many vulnerabilities in your code, the issue looks like you assume you always have a $_FILES. If you didn't upload a file, $_FILES['fileToUpload']['name']; is not going to exist. Check for it with if (isset($_FILES['fileToUpload'])) { and act on that information appropriately. You probably did get an error, or more specifically a warning, but it is in your web servers log file.

delete image from server folder

Here is code of uploading image in my localhost/file/img folder and also inserting image path and name in my table.
<?php
if (isset($_POST['submit']))
{
$file_id = $_POST['file_id'];
if (count($_FILES['upload']['name']) > 0)
{
for ($i = 0; $i < count($_FILES['upload']['name']); $i++)
{
$tmpFilePath = $_FILES['upload']['tmp_name'][$i];
if ($tmpFilePath != "")
{
$shortname = $_FILES['upload']['name'][$i];
$filePath = "img/" . $_FILES['upload']['name'][$i];
if (move_uploaded_file($tmpFilePath, $filePath))
{
$files[] = $shortname;
$query = "insert into images(id,img_name) values('$file_id',' $filePath')";
mysqli_query($con, $query);
}
}
}
}
echo "<h1>Uploaded:</h1>";
if (is_array($files))
{
echo "<ul>";
foreach($files as $file)
{
echo "<li>$file</li>";
}
echo "</ul>";
}
}
?>
Table Images with attribute img_name type is LONGBLOB
now its totally working fine but when i am deleting image from database its getting error that image name is not found. here is code of sending image id and image name using a href
<ul>
<a href="index.php?img_id=<?php echo urlencode($id); ?>&img=<?php echo urlencode($img); ?>"
style="color:red; margin-left:18px;" onclick="return confirm('Are you sure you want to delete this?')" >Delete
</a>
</ul>
now here is code of want i want to delete from my database and also from my localhost folder named img .
<?php
if (isset($_GET['img_id'], $_GET['img']))
{
$id = $_GET['img_id'];
$img = $_GET['img'];
$query = "delete from images where id='$id' and image='$img'";
if (mysqli_query($con, $query))
{
unlink($img);
echo '<script language="javascript">';
echo 'alert("Image Deleted successfully")';
echo '</script>';
}
else
{
echo '<script language="javascript">';
echo 'alert("image does not exist")';
echo '</script>';
}
}
?>
now showing warning that img/image_name.jpg not found.Help me please .
I think your delete query is wrong
if(isset($_GET['img_id'] , $_GET['img'])){
$id=$_GET['img_id'];
$img=$_GET['img'];
$query="delete from images where id='$id' and image='$id'";
}
$query="delete from images where id='$id' and image='$img'";
In this query you check Id and Image field with same $id variable
try this :
<?php
if (isset($_FILES['image']['name'])) {
$name = $_FILES['image']['name'];
$tmpname1 = $_FILES['image']['tmp_name'];
$exten = explode(".", $_FILES['image']['name']);
$exten = $exten[1];
if ($exten != '') {
$image_name = "img" . time() . "." . $exten;
}
move_uploaded_file($tmpname1, FCPATH . 'assets/admin/uploads/' . $image_name);
$query = "insert into images(id,img_name) values('your_id',' $image_name')";
mysqli_query($con, $query);
//see your code
/*
$id=$_GET['img_id'];
$img=$_GET['img'];
$query="delete from images where id='$id' and image='$id'";
*/
you pass the same id value for image. you should try this-
$query="delete from images where id='$id' and image='$img'";
}

Upload video with php and html

How can i upload a video ? i did this with a image file but is not working with a video one only showing "error"
<?php
session_start();
if( !isset($_SESSION["username"]) ){
echo "<p id='errors'>Por favor, loguese, si no es redireccionado haga click <a href='log.php'>aqui</a></p>";
header("location: log.php");
}else{
};
$img = $_GET["fileToUploadv"];
$target_dir = "video/";
$target_file = $target_dir . basename($_FILES["fileToUploadv"]["name"]);
$uploadOk = 1;
$imageFileType = strtolower(pathinfo($target_file,PATHINFO_EXTENSION));
// Check if image file is a actual image or fake image
if(isset($_POST["submit"])) {
$check = getimagesize($_FILES["fileToUploadv"]["tmp_name"]);
if($check !== false) {
$uploadOk = 1;
} else {
echo "The file is not an image!.";
$uploadOk = 0;
}
}
// Check if file already exists
// Check file size
// Allow certain file formats
if($imageFileType != "mp4" && $imageFileType != "mp4" ) {
echo "Only use a .JPG file.";
$uploadOk = 0;
}
if (file_exists($target_file)) {
unlink("video/video.mp4");
unlink("video/video.avi");
}
// Check if $uploadOk is set to 0 by an error
if ($uploadOk == 0) {
echo "Error.";
// if everything is ok, try to upload file
} else {
if (move_uploaded_file($_FILES["fileToUploadv"]["tmp_name"], $target_file)) {
echo "The file ". basename( $_FILES["fileToUploadv"]["name"]). " has been uploaded.";
rename("video/".basename( $_FILES["fileToUploadv"]["name"]), "video/video.mp4");
rename("video/".basename( $_FILES["fileToUploadv"]["name"]), "video/video.avi");
} else {
echo "Error.";
}
}
?>
this script have filetouploadv that is with a form input to upload mp4 or avi that is html
<form id="formimg" method="post" action="uploadvideo.php" enctype="multipart/form-data">
<label for="uploadimgg">
<p id="selectimg">Please select a MP4 or AVI file to upload.</p>
<i class="fas fa-upload"></i>
</label>
<input id="uploadimgg" type="file" name="fileToUploadv" accept="video/mp4,video/avi">
<input class="hideshowsub" id="submitpho" type="submit">
</form>
should change the name to video and upload to video/ but is not working ...move_uploaded_file because that reutrn false and do the "error" message
<?php
require("config.php");
$sql = "SELECT * FROM inventario";
$result = mysqli_query($link, $sql);
echo("<table>");
echo("<tr>");
echo ("<th class='midtable'>"."Username"."</th>");
echo ("<th class='midtable'>"."Password"."</th>");
echo ("<th class='midtable'>"."</th>");
echo ( "</tr>");
while ($row = mysqli_fetch_array($result))
{
echo("<tr>");
echo("<td><div class='data'>".$row['username']."</div><div class='edit'><input type='text' name='usrname' value='".$row['username']."'></div></td>"."<td><div class='data'".$row['password']."<div class='edit'><input type='text' name='password' value='".$row['password']."'></div></td>"."<td>"."<i class='fas fa-edit'></i>"."<i class='fas fa-trash-alt'></i>"."</td>" );
echo("</tr>") ;
}; ?>
and then using jQuery hide the class data and show the class edit elements in the row and a submit button to update the values in the DB... and perhaps update just that row...
You can't upload videos because of this:
if($check !== false)
Turn it from false to true:
if(isset($_POST["submit"])) {
$check = getimagesize($_FILES["fileToUploadv"]["tmp_name"]);
if($check !== true) {
$uploadOk = 1;
} else {
echo "The file is not an image!.";
$uploadOk = 0;
}
}

Pass PHP variable to MySQL database

I'm having trouble passing the value of a variable to a new record in MySQL database. I have created a form that the user fills out with basic information. Then they will upload an image. The PHP code renames the image with the next id to be assigned and concatenates the file type to create the new file name. I assign the new name to a variable $image with
$image = mysqli_insert_id($con) . "." . $imageFileType;
I can echo the variable and verify that is works fine - example 431.jpg would be the file name. Also, the image gets uploaded to the server with the correct renaming convention. Now I need to pass that value to the database when the form is submitted. It would be passed to the field name image in the database. So I have along with the other variables
$id = $_POST['id'];
$firstname = $_POST['firstname'];
$department = $_POST['department'];
$email = $_POST['email'];
$image = $_POST['image'];
I am trying to pass the value in the form using a hidden field that looks like this:
<input name="image" type="hidden" value="<?php echo $image; ?>" />
All the other data gets passed into the database except for the image name. I have tried many variations - even tried to use $_POST['$image'] for the value. Again, I can echo the value when the form is submitted so the value exists - I just can't pass it into the database record. I can get it to work if I enter the data in the form field manually. I have made the field type VARCHAR and TEXT in phpMyAdmin just to try different things.
If any can help that would be great.
Below is the $sqlinsert statement:
$sqlinsert = "INSERT INTO `test_2015`.`test_table` ( `id` , `firstname`, `department`, `email`, `image` )
VALUES ( '$id', '$firstname', '$department', '$email', '$image' )";
BELOW IS THE PHP:
<?php
if (isset($_POST['submitted'])){
include('connect.php');
// VARIABLES
$id = $_POST['id'];
$firstname = $_POST['firstname'];
$department = $_POST['department'];
$email = $_POST['email'];
$image = $_POST['image'];
$sqlinsert = "INSERT INTO `test_2015`.`test_table` ( `id` , `firstname`, `department`, `email`, `image` )
VALUES ( '$id', '$firstname', '$department', '$email', '$image' )";
//NESTED IF STATEMENT
// RUN THE QUERY
if ( !mysqli_query($con, $sqlinsert) )
{
die('error inserting new record');
} // END OF NESTED IF STATEMENT
// START IMAGE UPLOAD HERE ******************************************
$target_dir = "../images/";
$target_file = $target_dir . basename($_FILES["fileToUpload"]["name"]);
$uploadOk = 1;
$imageFileType = pathinfo($target_file,PATHINFO_EXTENSION);
$check = getimagesize($_FILES["fileToUpload"]["tmp_name"]);
if($check !== false) {
echo "File is an image - " . $check["mime"] . ".";
$uploadOk = 1;
} else {
echo "File is not an image.";
$uploadOk = 0;
}
//} REMOVE THIS IF ISSET END
// Check if file already exists
if (file_exists($target_file)) {
echo "Sorry, file already exists. ";
$uploadOk = 0;
}
// Allow certain file formats
if($imageFileType != "jpg" && $imageFileType != "png" && $imageFileType != "jpeg" && $imageFileType != "gif" ) {
echo "Sorry, only JPG, JPEG, PNG & GIF files are allowed.";
$uploadOk = 0;
}
// Check if $uploadOk is set to 0 by an error
if ($uploadOk == 0) {
echo "<div style ='font:16px Arial,tahoma,sans-serif;color:#ff0000;font-weight:bold'>File was not uploaded.</div>";
// if everything is ok, try to upload file
} else {
$imageName = mysqli_insert_id($con) . "." . $imageFileType;
if (move_uploaded_file($_FILES["fileToUpload"]["tmp_name"], $imageName ))
{
// CHANGE FILE NAME TO CURRENT ID
// USING mysqli_insert_id($con) TO GET ID AND CONCATENATE FILE TYPE
echo "New IMAGE file name is : ", $imageName;
// PASS NAME FOR IMAGE TO $image HERE
$image = $imageName;
echo "image = : ", $image;
echo "The file ". basename( $_FILES["fileToUpload"]["name"]). " has been uploaded.";
echo "<br>";
// GET THE ASSIGNED ID USING: mysqli_insert_id()
echo "New Record ID is : " . mysqli_insert_id($con);
} else {
echo "<div style ='font:16px Arial,tahoma,sans-serif;color:#ff0000;font-weight:bold'>
Sorry, there was an error uploading your file.</div>";
echo "<br>";
}
}
// END IMAGE UPLOAD HERE ******************************************
$newrecord = "1 record added to the database";
echo "<br>";
} // END MAIN IF STATEMENT
// Close connection
mysqli_close($con);
?>
BELOW IS MY FORM:
<form method="post" action="add_record.php" enctype="multipart/form-data">
<input type="hidden" name="submitted" value="true" />
<fieldset>
<legend>New Record</legend>
<label><input type="hidden" name="id" /></label>
<label>First Name : <input type="text" name="firstname" required="required" /></label><br /><br />
<label>Department : <input type="text" name="department" required="required" /></label><br /><br />
<label>Email Address : <input type="text" name="email" required="required" /></label><br /><br />
<label>Image Name: <input name="image" type="hidden" value="<?php echo $image; ?>" /></label>
</fieldset>
<br />
Select image to upload:
<input type="file" name="fileToUpload" id="fileToUpload">
<input type="submit" value="add new record button" />
</form>
RESULTS FROM var_dump($POST);
array(6) { ["submitted"]=> string(4) "true" ["id"]=> string(0) "" ["firstname"]=> string(10) "first_name" ["department"]=> string(10) "department" ["email"]=> string(5) "email" ["image"]=> string(0) "" }
The problem is when you run the insert query $image is just an empty string (derived from an empty hidden input). I kind of understand why its there, something to do with validation failure, not that it helps much as the file would need to be re-selected if that were the case.
Add this:
$image = mysqli_real_escape_string ($con , $image);
$queryStr = "update `test_2015`.`test_table` set `image`= '$image' where `id`=" . mysqli_insert_id($con);
mysqli_query($con, $queryStr);
After:
$image = $imageName;
(about 20 lines up from the bottom of your script)
Since your primary goal is to save that file name generated in image field consider the following php code:
<?php
if (isset($_POST['submitted'])){
include('connect.php');
// VARIABLES
$id = $_POST['id'];
$firstname = $_POST['firstname'];
$department = $_POST['department'];
$email = $_POST['email'];
$image = $_POST['image'];
$sqlinsert = "INSERT INTO `test_2015`.`test_table` ( `id` , `firstname`, `department`, `email`, `image` )
VALUES ( '$id', '$firstname', '$department', '$email', '$image' )";
//NESTED IF STATEMENT
// RUN THE QUERY
if ( !mysqli_query($con, $sqlinsert) )
{
die('error inserting new record');
} // END OF NESTED IF STATEMENT
// START IMAGE UPLOAD HERE ******************************************
$target_dir = "../images/";
$target_file = $target_dir . basename($_FILES["fileToUpload"]["name"]);
$uploadOk = 1;
$imageFileType = pathinfo($target_file,PATHINFO_EXTENSION);
$check = getimagesize($_FILES["fileToUpload"]["tmp_name"]);
if($check !== false) {
echo "File is an image - " . $check["mime"] . ".";
$uploadOk = 1;
} else {
echo "File is not an image.";
$uploadOk = 0;
}
//} REMOVE THIS IF ISSET END
// Check if file already exists
if (file_exists($target_file)) {
echo "Sorry, file already exists. ";
$uploadOk = 0;
}
// Allow certain file formats
if($imageFileType != "jpg" && $imageFileType != "png" && $imageFileType != "jpeg" && $imageFileType != "gif" ) {
echo "Sorry, only JPG, JPEG, PNG & GIF files are allowed.";
$uploadOk = 0;
}
// Check if $uploadOk is set to 0 by an error
if ($uploadOk == 0) {
echo "<div style ='font:16px Arial,tahoma,sans-serif;color:#ff0000;font-weight:bold'>File was not uploaded.</div>";
// if everything is ok, try to upload file
} else {
$imageName = mysqli_insert_id($con) . "." . $imageFileType;
if (move_uploaded_file($_FILES["fileToUpload"]["tmp_name"], $imageName ))
{
// CHANGE FILE NAME TO CURRENT ID
// USING mysqli_insert_id($con) TO GET ID AND CONCATENATE FILE TYPE
echo "New IMAGE file name is : ", $imageName;
// PASS NAME FOR IMAGE TO $image HERE
$image = $imageName;
echo "image = : ", $image;
echo "The file ". basename( $_FILES["fileToUpload"]["name"]). " has been uploaded.";
echo "<br>";
// GET THE ASSIGNED ID USING: mysqli_insert_id()
echo "New Record ID is : " . mysqli_insert_id($con);
// SAVE New IMAGE file name
$sqlupdate = "UPDATE `test_2015`.`test_table` SET `image` = '$image' WHERE id = " . mysqli_insert_id($con);
if ( !mysqli_query($con, $sqlupdate) )
{
die('error updating new record');
}
} else {
echo "<div style ='font:16px Arial,tahoma,sans-serif;color:#ff0000;font-weight:bold'>
Sorry, there was an error uploading your file.</div>";
echo "<br>";
}
}
// END IMAGE UPLOAD HERE ******************************************
$newrecord = "1 record added to the database";
echo "<br>";
} // END MAIN IF STATEMENT
// Close connection
mysqli_close($con);
?>
The code that I added are the following:
// SAVE New IMAGE file name
$sqlupdate = "UPDATE `test_2015`.`test_table` SET `image` = '$image' WHERE id = " . mysqli_insert_id($con);
if ( !mysqli_query($con, $sqlupdate) )
{
die('error updating new record');
}
The idea here is to update your newly inserted record when you've successfully generated the new file name of your image. You can't save the image file name when inserting the new record since id is not yet generated so your only choice is to update it.
I don't think you need that hidden input named 'image' in your form if your only goal is to save the newly generated image file name unless you have other use for it.

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.

Categories