Pass PHP variable to MySQL database - php

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.

Related

Updating Mysqli database with all file names from the upload form

I found this code and it all works file uploads to the correct folder that is fine.
image - is main image that works it inserts one image name into the database field.
but when i try to insert all the names of the files uploaded in images field it only inserts the last file name.
$imageDirectory = "img/cars/" . $resultget->id . "";
$newDirName = generateRandomString(10);
$targetDir = $imageDirectory."/";
if (!file_exists($targetDir)) {
mkdir($targetDir, 0777, true);
} else {
$targetDir = $imageDirectory."/";
}
// Count total files
$fileCount = count($_FILES['the_file']['name']);
// Iterate through the files
for($i = 0; $i < $fileCount; $i++){
$target_dir = $imageDirectory."/";
$target_file = $target_dir . basename($_FILES["the_file"]["name"][$i]);
$uploadOk = 1;
$imageFileType = strtolower(pathinfo($target_file,PATHINFO_EXTENSION));
// Check if image file is a actual image or fake image
$check = getimagesize($_FILES["the_file"]["tmp_name"][$i]);
if($check !== false) {
//echo "File is an image - " . $check["mime"] . ".";
$uploadOk = 1;
} else {
$errorTxt = "File is not an image.";
$uploadOk = 0;
}
// Check if file already exists
if (file_exists($target_file)) {
$errorTxt = "Sorry, file already exists.";
$uploadOk = 0;
}
// Check file size
// if ($_FILES["new_young"]["size"] > 500000) {
// $errorTxt = "Sorry, your file is too large.";
// $uploadOk = 0;
// }
// Allow certain file formats
if($imageFileType != "jpg" && $imageFileType != "png" && $imageFileType != "jpeg"
&& $imageFileType != "gif" ) {
$errorTxt = "Sorry, only JPG, JPEG, PNG & GIF files are allowed.";
$uploadOk = 0;
}
// Check if $uploadOk is set to 0 by an error
$temp = explode(".", $_FILES["the_file"]["name"][$i]);
$newfilename = str_replace( '.', '', strval( microtime( true ) ) ) . '.' . end( $temp );
$target_file = $target_dir . $newfilename;
if (file_exists($target_file)) {
$errorTxt = "Sorry, file already exists.";
$uploadOk = 0;
}
if ($uploadOk == 0) {
// if everything is ok, try to upload file
echo $errorTxt;
} else {
if (move_uploaded_file($_FILES["the_file"]["tmp_name"][$i], $target_file )) {
$checking = $resultget->images;
$checkimage = $resultget->image;
if(empty($checkimage)) {
$sqlimage = "UPDATE individual_cars SET image = '$newfilename' WHERE id = '$image_id'";
mysqli_query($mysqli, $sqlimage) or die(mysqli_error($mysqli));
}
foreach (array($newfilename) as $filename) {
if(empty($checking)) {
echo implode(',', $filename);
$sqlimage = "UPDATE individual_cars SET images = '" . implode(',', $filename) . "' WHERE id = '" . $resultget->id . "'";
mysqli_query($mysqli, $sqlimage) or die(mysqli_error($mysqli));
} else {
echo implode(',', $filename);
$sqlimage = "UPDATE individual_cars SET images = '," . implode(',', $filename) . "' WHERE id = '" . $resultget->id . "'";
mysqli_query($mysqli, $sqlimage) or die(mysqli_error($mysqli));
}
}
} else {
$errorTxt = "Sorry, there was an error uploading your file.";
}
}
}
Im checking images if empty because if a file name is already in that field i want it to continue so like this
example: 12345.png is already in there so if its not empty i want 12345.png, 54321.png and so on.
but its only inserting the last image name
sorry this is my first time posting.

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

How do I add images to my PHP blog?

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

How do i get the id of a submitted "new product" through my form, so i can rename an image submitted with it?

This is my code, and the image is uploaded where i want it to, but its named 0."file extension" everytime, but i want the image to have the same name as the id of the object im submitting with this form.
id: 3
img name: 3."file extension"
My php:
<?php
if (isset($_POST['submit_newProduct'])) { // Form has been submitted.
$errors = array();
// perform validations on the form data and avoid sql injection
$product_name = trim(mysqli_real_escape_string($connection, $_POST['product_name']));
$product_price = trim(mysqli_real_escape_string($connection, $_POST['product_price']));
$product_desc = trim(mysqli_real_escape_string($connection, $_POST['product_desc']));
$product_category = trim(mysqli_real_escape_string($connection, $_POST['product_category']));
$product_attribute = trim(mysqli_real_escape_string($connection, $_POST['product_attribute']));
$query = "INSERT INTO products
(product_name, product_price, product_desc,
product_category, product_attribute)
VALUES ('{$product_name}', '{$product_price}',
'{$product_desc}', '{$product_category}',
'{$product_attribute}')";
$filename = $_FILES["product_img"]["name"];
$file_basename = substr($filename, 0, strripos($filename, '.')); // get file extention
$file_ext = substr($filename, strripos($filename, '.')); // get file name
$filesize = $_FILES["product_img"]["size"];
$allowed_file_types = array('.png','.jpg','.jpeg','.gif');
if (in_array($file_ext,$allowed_file_types) && ($filesize < 200000)) {
// Rename file
$pid = mysqli_insert_id($connection);
$newfilename = $pid . $file_ext;
if (file_exists("img/product_img/" . $newfilename))
{
// file already exists error
echo "You have already uploaded this file.";
}
else
{
move_uploaded_file($_FILES["product_img"]["tmp_name"], "img/product_img/" . $newfilename);
echo "File uploaded successfully.";
}
}
elseif (empty($file_basename))
{
// file selection error
echo "Please select a file to upload.";
}
elseif ($filesize > 200000)
{
// file size error
echo "The file you are trying to upload is too large.";
}
else
{
// file type error
echo "Only these file typs are allowed for upload: " . implode(', ',$allowed_file_types);
unlink($_FILES["file"]["tmp_name"]);
}
header("location:product_list.php"); //maskes sure item is not recreated on refresh
$result = mysqli_query($connection, $query);
if ($result) {
$message = "Produkt oprettet.";
} else {
$message = "Der skete en fejl";
$message .= "<br />" . mysqli_error($connection);
}
}
?>
My html form:
<form action="" method="post" enctype="multipart/form-data">
<div class="col-md-6">
<h4>Produkt navn</h4>
<input type="text" name="product_name" class="form-control"> <br>
<h4>Produkt pris</h4>
<input type="text" placeholder="DKK" name="product_price" class="form-control" style="width:30%;"><br>
<h4>Produkt beskrivelse</h4>
<textarea type="text" name="product_desc" rows="3" class="form-control"></textarea> <br>
<h4>Produkt kategori</h4>
<select name="product_category" class="form-control">
<option></option>
<option>Gummi ænder</option>
<option>Påklædning</option>
<option>Accessories</option>
</select> <br>
<h4>Produkt attribut</h4>
<input type="text" name="product_attribute" class="form-control" value=""> <br>
<input type="file" name="product_img"><br>
<input type="submit" name="submit_newProduct" class="btn btn-warning pull-right" value="Tilføj produkt">
</div>
</form>
Since, Query is executing after mysqli_insert_id(); Thats why it is returning 0.
Place your query before mysqli_insert_id(), then only you will get inserted id.
I placed / edited your code in my way. You can change it accordingly.
<?php
if (isset($_POST['submit_newProduct'])) { // Form has been submitted.
$errors = array();
// perform validations on the form data and avoid sql injection
$product_name = trim(mysqli_real_escape_string($connection, $_POST['product_name']));
$product_price = trim(mysqli_real_escape_string($connection, $_POST['product_price']));
$product_desc = trim(mysqli_real_escape_string($connection, $_POST['product_desc']));
$product_category = trim(mysqli_real_escape_string($connection, $_POST['product_category']));
$product_attribute = trim(mysqli_real_escape_string($connection, $_POST['product_attribute']));
$query = "INSERT INTO products (product_name, product_price, product_desc, product_category, product_attribute)
VALUES ('{$product_name}', '{$product_price}', '{$product_desc}', '{$product_category}', '{$product_attribute}')";
$result = mysqli_query($connection, $query);
if ($result) {
$filename = $_FILES["product_img"]["name"];
$file_basename = substr($filename, 0, strripos($filename, '.')); // get file extention
$file_ext = substr($filename, strripos($filename, '.')); // get file name
$filesize = $_FILES["product_img"]["size"];
$allowed_file_types = array('.png','.jpg','.jpeg','.gif');
if (in_array($file_ext,$allowed_file_types) && ($filesize < 200000)) {
// Rename file
$pid = mysqli_insert_id($connection);
$newfilename = $pid . $file_ext;
if (file_exists("img/product_img/" . $newfilename)){
// file already exists error
echo "You have already uploaded this file.";
} else {
move_uploaded_file($_FILES["product_img"]["tmp_name"], "img/product_img/" . $newfilename);
echo "File uploaded successfully.";
}
}
elseif (empty($file_basename)){
// file selection error
echo "Please select a file to upload.";
}
elseif ($filesize > 200000){
// file size error
echo "The file you are trying to upload is too large.";
}
else{
// file type error
echo "Only these file typs are allowed for upload: " . implode(', ',$allowed_file_types);
unlink($_FILES["file"]["tmp_name"]);
}
$message = "Produkt oprettet.";
}
else {
$message = "Der skete en fejl";
$message .= "<br />" . mysqli_error($connection);
}
header("location:product_list.php"); //maskes sure item is not recreated on refresh
}
?>

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