How to update old image if no image selected in php - php

I can all input type values view in my update page but, I can't display file input value for ex: photo. Here I can be displayed image location value in a separate part.
My problem for
When I update the only name or mother name or anyone without photo all fields values update correctly but my image is updated empty values. when I update with a photo and other details then only my photo updated correctly. so help me how to update photo values with edit without edit.....
update.php
<!doctype html>
<html>
<body>
<?php
error_reporting(E_ALL ^ E_DEPRECATED);
$upd = $_GET['upd'];
mysql_connect('localhost','root','');
mysql_select_db("display");
$slc = "SELECT * from photos WHERE firstname = '$upd'";
$run = mysql_query($slc);
while($row=mysql_fetch_array($run)){
$firstname = $row['firstname'];
$lastname = $row['lastname'];
$location=$row['location'];
}
?>
<div class="update">
<table align="center" border="">
<tr>
<td colspan="4"><center><h1 style="color:red">Student Form Updation</h1>
</center></td></tr>
<form method="post" enctype="multipart/form-data" action="update.php?upd=<?
php echo $firstname; ?> "/>
<tr><td><label>First Name:</label></td><td>
<input type="text" name="firstname" value="<?php echo $firstname ?> " />
</td>
<td><label>Last Name:</label></td><td>
<input type="text"name="lastname" value="<?php echo $lastname?>" /></td>
</tr>
<td><label>Select Photo</label></td>
<td> <input type="file" name="image" class="ed" id="location" value= "<?php
echo $location?>"/> <?php echo '<img width="100px" height="100px"
src="'.$location.'">'; ?>
</td>
</tr>
<tr><td></td><td><input type="submit" name="update" value="Update"
id="button1" /></td>
<td><input type="submit" formaction="errview.php" value="View" id="button1"
/></td><td></td></tr>
</form>
</div>
<?php
if(isset($_POST['update']))
{
$nid = $_GET['upd'];
$firstname = $_POST['firstname'];
$lastname = $_POST['lastname'];
$file=$_FILES['image']['tmp_name'];
$image=addslashes(file_get_contents($_FILES['image']['tmp_name']));
$image_name= addslashes($_FILES['image']['name']);
move_uploaded_file($_FILES["image"]["tmp_name"],"photos/" . $_FILES["image"]
["name"]);
$location="photos/" . $_FILES["image"]["name"];
$update = "UPDATE photos SET firstname='$firstname', lastname =
'$lastname',location='$location' WHERE firstname='$nid'";
$run = mysql_query($update);
echo "<script>alert('Update SuccessFull!');location.href='update.php?
upd=$firstname'</script>";
}
?>
</body>
</html>

You Can Modify Your Update Code Like This:
If no image is selected It will not Update Your Image in Database It Will Only Update Your Image in the database if an image is selected
<?php
if (isset($_POST['update'])) {
$nid = $_GET['upd'];
$firstname = $_POST['firstname'];
$lastname = $_POST['lastname'];
$file = $_FILES['image']['tmp_name'];
$image = addslashes(file_get_contents($_FILES['image']['tmp_name']));
$image_name = addslashes($_FILES['image']['name']);
move_uploaded_file($_FILES["image"]["tmp_name"], "photos/" . $_FILES["image"]["name"]);
$location = "photos/" . $_FILES["image"]["name"];
if ((!($_FILES['image']['name']))) /* If there Is No file Selected*/ {
$update = "UPDATE photos SET firstname='$firstname', lastname =
'$lastname' WHERE firstname='$nid'";
} else /* If file is Selected*/ {
$update = "UPDATE photos SET firstname='$firstname', lastname =
'$lastname',location='$location' WHERE firstname='$nid'";
}
$run = mysql_query($update);
echo "<script>alert('Update SuccessFull!');location.href='update.php?
upd=$firstname'</script>";
}
?>

<?php
if(empty($image)){
$product_img1=$row_edit['image'];
}
else{
$temp_name1=$_FILES['product_img1']['tmp_name'];
move_uploaded_file($temp_name1,"product_images/$product_img1");
}
?>

Related

file upload (php) two warnings

I am working on small page where I update MySQL records via PHP page, all the functionality is well working but I constantly get warnings for an Undefined array.
Here are the warnings:
Warning: Undefined array key "file" in C:\xampp\htdocs\crud\edit.php on line 11
Warning: Trying to access array offset on value of type null in C:\xampp\htdocs\crud\edit.php on line 11
Warning: Undefined array key "file" in C:\xampp\htdocs\crud\edit.php on line 22
Warning: Trying to access array offset on value of type null in C:\xampp\htdocs\crud\edit.php on line 22
I was looking at many topics like this but did not manage to fix my own one...
Here is the code of edit.php
include 'db.php';
// File upload path
$targetDir = "uploads/";
$fileName = basename($_FILES["file"]["name"]);
$targetFilePath = $targetDir . $fileName;
$fileType = pathinfo($targetFilePath,PATHINFO_EXTENSION);
if(isset($_POST["submit"]) && !empty($_FILES["file"]["name"])){
}
// Allow certain file formats
$allowTypes = array('jpg','png','jpeg','gif','pdf','doc','xlsx');
if(in_array($fileType, $allowTypes)){
}
// Upload file to server
if(move_uploaded_file($_FILES["file"]["tmp_name"], $targetFilePath)){
}
I have also a pcs of HTML for that in <form:
<form name="update_user" method="post" action="edit.php" enctype="multipart/form-data" >
<tr>
<td>Нов сертификат:</td>
<td><input type="file" name="file" ></td>
</tr>
I have a feeling that I missed something very simple.
----- update -------
here is my full code: in one file I put php with the html
// include database connection file
include_once("config.php");
//тук стартирам за фаил ъплоад
// Include the database configuration file
include 'db.php';
// File upload path
$targetDir = "uploads/";
$fileName = basename($_FILES["file"]["name"]);
$targetFilePath = $targetDir . $fileName;
$fileType = pathinfo($targetFilePath,PATHINFO_EXTENSION);
if(isset($_POST["submit"]) && !empty($_FILES["file"]["name"])){
}
// Allow certain file formats
$allowTypes = array('jpg','png','jpeg','gif','pdf','doc','xlsx');
if(in_array($fileType, $allowTypes)){
}
// Upload file to server
if(move_uploaded_file($_FILES["file"]["tmp_name"], $targetFilePath)){
}
// край на фаил ъплоад
// Check if form is submitted for user update, then redirect to homepage after update
if(isset($_POST['update']))
{
$id = $_POST['id'];
$toolnr=$_POST['toolnr'];
$status=$_POST['status'];
$toolname=$_POST['toolname'];
$serial=$_POST['serial'];
$usedat=$_POST['usedat'];
$owner=$_POST['owner'];
$calibrated=$_POST['calibrated'];
$nextcalibration=$_POST['nextcalibration'];
$vendors=$_POST['vendors'];
// update user data
$result = mysqli_query($mysqli, "UPDATE tools SET toolnr='$toolnr',status='$status',toolname='$toolname',serial='$serial',usedat='$usedat',owner='$owner',calibrated='$calibrated',nextcalibration='$nextcalibration', vendors='$vendors', file_name = '$fileName' WHERE id='$id'");
// Redirect to homepage to display updated user in list
header("Location: index.php");
}
?>
<?php
// Display selected user data based on id
// Getting id from url
$id = $_GET['id'];
// Fetech user data based on id
$result = mysqli_query($mysqli, "SELECT * FROM tools WHERE id=$id");
while($user_data = mysqli_fetch_array($result))
{
$toolnr = $user_data['toolnr'];
$status = $user_data['status'];
$toolname = $user_data['toolname'];
$serial = $user_data['serial'];
$usedat = $user_data['usedat'];
$owner = $user_data['owner'];
$calibrated = $user_data['calibrated'];
$nextcalibration = $user_data['nextcalibration'];
$vendors = $user_data['vendors'];
$momenten = $user_data['file_name'];
}
?>
<html>
<head>
<title>Актуализация</title>
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap#4.6.2/dist/css/bootstrap.min.css" integrity="sha384-xOolHFLEh07PJGoPkLv1IbcEPTNtaed2xpHsD9ESMhqIYd0nLMwNLD69Npy4HI+N" crossorigin="anonymous">
<center> <img src="logo-ottobock.png" alt="OttobockLogo"> </center>
<hr> <br>
<center> <img src="notification.png" alt="Warning"> </center>
<center> <i> <p style="color:red;"> В момента работите с най-високо ниво на достъп, моля бъдете внимателни. <br> Всички направени от Вас промени са необратими. <p> </i> </center>
</head>
<body>
<br/><br/>
<center> <form name="update_user" method="post" action="edit.php" enctype="multipart/form-data" >
<table border="0" class="table table-striped" >
<tr>
<td>Номер</td>
<td><input type="text" name="toolnr" class="form-control" value=<?php echo $toolnr;?>></td>
</tr>
<tr>
<td>Статус</td>
<td>
<select name="status" id="status" class="form-control" required>
<?php
include "dbConn.php";
$records = mysqli_query($db, "SELECT status FROM tools WHERE id=$id UNION SELECT currentstatus FROM statuses");
while($data = mysqli_fetch_array($records))
{
echo "<option value='". $data['status'] ."'>" .$data['status'] ."</option>";
}
?> </select>
</td>
</tr>
<tr>
<td>Найменование</td>
<td><input type="text" name="toolname" class="form-control" value="<?php echo $toolname;?>"></td>
</tr> <br>
<tr>
<td>Сериен номер</td>
<td><input type="text" name="serial" class="form-control" value="<?php echo $serial;?>"></td>
</tr>
<tr>
<td>Локация</td>
<td>
<select name="usedat" id="usedat" class="form-control" required>
<?php
include "dbConn.php";
$records = mysqli_query($db, "SELECT usedat FROM tools WHERE id=$id UNION SELECT locations From whereused");
while($data = mysqli_fetch_array($records))
{
echo "<option value='". $data['usedat'] ."'>" .$data['usedat'] ."</option>";
}
?> </select>
</td>
</tr>
<tr>
<td>Отговорник</td>
<td>
<select name="owner" id="owner" class="form-control" required>
<?php
include "dbConn.php";
$records = mysqli_query($db, "SELECT owner FROM tools WHERE id=$id UNION SELECT responsiblepersons From responsibles");
while($data = mysqli_fetch_array($records))
{
echo "<option value='". $data['owner'] ."'>" .$data['owner'] ."</option>";
}
?> </select>
</td>
</tr>
<tr>
<td>Калибриран на:</td>
<td><input type="date" name="calibrated" class="form-control" value=<?php echo $calibrated;?>></td>
</tr>
<tr>
<td>Следваща</td>
<td><input type="date" name="nextcalibration" class="form-control" value=<?php echo $nextcalibration;?>></td>
</tr>
<tr>
<td>Сертификат</td>
<td><?php echo "<a target = '_blank' href='http://10.171.2.15/crud/uploads/$momenten'> Свали </a>";?></td>
</tr>
<tr>
<td>Нов сертификат:</td>
<td><input type="file" name="file" ></td>
</tr>
<tr>
<td>Калибрира се при</td>
<td>
<select name="vendors" id="vendors" class="form-control" required>
<?php
include "dbConn.php";
$records = mysqli_query($db, "SELECT vendors FROM tools WHERE id=$id UNION SELECT vendoren FROM vendors");
while($data = mysqli_fetch_array($records))
{
echo "<option value='". $data['vendors'] ."'>" .$data['vendors'] ."</option>";
}
?> </select>
</td>
</tr>
<tr>
<td><input type="hidden" name="id" value=<?php echo $_GET['id'];?>></td>
<td><input type="submit" name="update" class="btn btn-success" value="Запис">
<a href="index.php" class="btn btn-danger" >Отказ</a> </td>
</tr>
</table>
</form> </center>
</body>
Posting working code:
final-fixed code (only php part). The problem was that the part of the code responsible for file upload was out of the if statement
<?php
// include database connection file
include_once("config.php");
// Check if form is submitted for user update, then redirect to homepage after update
if(isset($_POST['update']))
{
$id = $_POST['id'];
$toolnr=$_POST['toolnr'];
$status=$_POST['status'];
$toolname=$_POST['toolname'];
$serial=$_POST['serial'];
$usedat=$_POST['usedat'];
$owner=$_POST['owner'];
$calibrated=$_POST['calibrated'];
$nextcalibration=$_POST['nextcalibration'];
$vendors=$_POST['vendors'];
// Include the database configuration file
include 'db.php';
$statusMsg = '';
// File upload path
$targetDir = "uploads/";
$fileName = basename($_FILES["file"]["name"]);
$targetFilePath = $targetDir . $fileName;
$fileType = pathinfo($targetFilePath,PATHINFO_EXTENSION);
if(isset($_POST["submit"]) && !empty($_FILES["file"]["name"])){
// Allow certain file formats
$allowTypes = array('jpg','png','jpeg','gif','pdf','doc','xlsx');
if(in_array($fileType, $allowTypes)){
}
}
// Upload file to server
if(move_uploaded_file($_FILES["file"]["tmp_name"], $targetFilePath)){
}
// update user data
$result = mysqli_query($mysqli, "UPDATE tools SET toolnr='$toolnr',status='$status',toolname='$toolname',serial='$serial',usedat='$usedat',owner='$owner',calibrated='$calibrated',nextcalibration='$nextcalibration', vendors='$vendors', file_name = '$fileName' WHERE id='$id'");
// Redirect to homepage to display updated user in list
header("Location: index.php");
}
?>

Why are values from a url are not being passed to sticky form

I have created a php sticky form so data will not disappear when the submit button is clicked. A url link is being used to pass values to a form so they can be edited. However, the values from the url are not being passed into the form fields. Why are the values from the url not being passed into the form fields? Thank you so much for your time.
This is the code:
index.php
<?php
require_once('authorize.php');
?>
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<?php
require_once('appvars.php');
require_once('connectvars.php');
$conn = mysqli_connect(DB_HOST, DB_USER, DB_PASSWORD, DB_NAME);
$data = mysqli_query($conn, $query);
echo '<table>';
echo '<tr><th>Name</th><th>Caption</th><th>Action</th></tr>';
while ($row = mysqli_fetch_array($data)) {
//link
echo '<td><a href="link.php?id=' . $row['id'] . '&image=' . $row['image1'] . '&name=' . $row['name'] .
'&caption=' . $row['caption'] .
'&video=' . $row['video'] . '">Edit </a>';
echo '</td></tr>';
}
echo '</table>';
echo "<br><br>";
mysqli_close($conn);
?>
</body>
</html>
sticky_form.php
<!DOCTYPE html>
<html>
<head>
<title>Edit Conent</title>
</head>
<body>
<h3>Edit Conent</h3>
<?php
require_once('appvars.php');
require_once('connectvars.php');
$vid="";
$vname="";
$vcaption="";
$vvideo="";
$id ="";
$dbc = mysqli_connect(DB_HOST, DB_USER, DB_PASSWORD, DB_NAME);
if(isset($_POST["button_edit"])){
$id = $_POST["id"];
$name = $_POST['name'];
$caption = $_POST['caption'];
$video = $_POST['video'];
$qry = mysqli_query($dbc,"Update table1 Set name='$name', caption='$caption', video='$video' Where id='$id'");
else if(isset($_GET["id"])){
$qry = mysqli_query($dbc,"Select * From table1 Where id='".$_GET["id"]."'");
while($row=mysqli_fetch_array($qry,MYSQLI_ASSOC)){
$vid=$row["id"];
$vname=$row["name"];
$vcaption=$row["caption"];
$vvideo=$row["video"];
}
}
?>
<body>
<form action='' method="post" enctype="multipart/form-data" >
<table>
<tr>
<td>ID</td>
<td><input type="text" name="id" value="<?php echo $vid;?>"></td></tr>
<tr>
<td>Name</td>
<td><input type="text" class="bigger_textbox" name="name" value="<?php if (isset($_POST['name'])) {echo htmlentities($_POST['name']);}?>"></td></tr>
<tr><td>Caption</td>
<td><input type="text" class="bigger_textbox" name="caption" value="<?php if (isset($_POST['caption'])) {echo htmlentities($_POST['caption']);}?>"></td></tr>
<tr><td>Video</td>
<td><input type="text" class="bigger_textbox" name="video" value="<?php if (isset($_POST['video'])) {echo htmlentities($_POST['video']);}?>"></td></tr>
<tr><td colspan="2">
<input type="submit" name="button_edit" value="Edit Content"></td></tr> </table>
</form>
<table border=1>
<tr><th>Name</th><th>Caption</th>
<th>Video</th> <th>Action</th></tr>
<?php
if (isset($_GET["id"])) {
$qry =mysqli_query($dbc, "Select * From table1 Where id='".$_GET["id"]."'");
while($row=mysqli_fetch_array($qry,MYSQLI_ASSOC)) {
echo '<tr><td>'.$row["name"].'</td>';
echo '<td>'.$row["caption"].'</td>';
echo '<td>'.$row["video"].'</td>';
echo '<td>Edit </td></tr>';
}
}
?>
</table>
</body>
</html>
Apparently you already have the values you need in stick_form.php:
else if(isset($_GET["id"])){
$qry = mysqli_query($dbc,"Select * From table1 Where id='".$_GET["id"]."'");
while($row=mysqli_fetch_array($qry,MYSQLI_ASSOC)){
$vid=$row["id"];
$vname=$row["name"];
$vcaption=$row["caption"];
$vvideo=$row["video"];
}
Try replacing this part of the code of stick_form.php:
<td><input type="text" class="bigger_textbox" name="name" value="<?php if (isset($_POST['name'])) {echo htmlentities($_POST['name']);}?>"></td></tr>
<tr><td>Caption</td>
<td><input type="text" class="bigger_textbox" name="caption" value="<?php if (isset($_POST['caption'])) {echo htmlentities($_POST['caption']);}?>"></td></tr>
<tr><td>Video</td>
<td><input type="text" class="bigger_textbox" name="video" value="<?php if (isset($_POST['video'])) {echo htmlentities($_POST['video']);}?>" </td></tr>
With:
<td><input type="text" class="bigger_textbox" name="name" value="<?php echo $vname; ?>"></td></tr>
<tr><td>Caption</td>
<td><input type="text" class="bigger_textbox" name="caption" value="<?php echo $vcaption; ?>"></td></tr>
<tr><td>Video</td>
<td><input type="text" class="bigger_textbox" name="video" value="<?php echo $vvideo; ?>"></td></tr>
Update
As you commented, after clicking the edit button, your form fields get empty. That's because you're not setting the correct variables in this part of your code:
if(isset($_POST["button_edit"])){
$id = $_POST["id"];
$name = $_POST['name'];
$caption = $_POST['caption'];
$video = $_POST['video'];
$qry = mysqli_query($dbc,"Update table1 Set name='$name', caption='$caption', video='$video' Where id='$id'");
Change it to:
if(isset($_POST["button_edit"])){
$vid = $_POST["id"];
$vname = $_POST['name'];
$vcaption = $_POST['caption'];
$vvideo = $_POST['video'];
$qry = mysqli_query($dbc,"Update table1 Set name='$vname', caption='$vcaption', video='$vvideo' Where id='$vid'");
Hope it helps.

Updating an image and text at the same time in Php and Mysql

Users can add, edit and delete content on my web page. People can edit the text and the image they upload. However, the image will not display if I only edit the text. When I edit the text but not the image, a white box is displayed where the image should appear. On the other hand, the image will appear if I only edit the photo but nothing else. Only the text will update when I try to edit both the image and text together.I want the user to be able to edit their text and image like they can on a profile page. Once the text and the image is edited, I want the old image to be deleted out of the folder. How can I edit the image and the text together? I am not getting any errors. Please help, I'm new to Php and MySQL. Thank you for your time. This is the code:
<?php
include "connection.php";
$vid="";
$vname="";
$vprice="";
if(isset($_POST["button_add"])){
$product_name = $_POST["product_name"];
$product_price = $_POST["product_price"];
$product_picture = $_FILES["product_picture"]["name"];
$qry = mysqli_query($con, "INSERT INTO table_product values('','$product_name','$product_price','$product_picture')") or die("Can not query database" );
if($qry){
$target_dir = "picture/";
$target_file = $target_dir . basename($_FILES["product_picture"]["name"]);
$imageFileType = pathinfo($target_file,PATHINFO_EXTENSION);
if(move_uploaded_file($_FILES["product_picture"]["tmp_name"],
$target_file)){
echo"file uploaded";
}
else{
echo "Upload fail";
}
}
}
else if(isset($_POST["button_edit"])){
$product_name = $_POST["product_name"];
$product_price = $_POST["product_price"];
$product_id = $_POST["product_id"];
if(isset($_FILES["product_picture"]["name"])){
$product_picture = $_FILES["product_picture"]["name"];
$qry = mysqli_query($con,"Update table_product Set product_name='$product_name', product_price='$product_price', product_picture='$product_picture' Where product_id='$product_id'");
$target_dir = "picture/";
$target_file = $target_dir . basename($_FILES["product_picture"]["name"]);
$imageFileType = pathinfo($target_file,PATHINFO_EXTENSION);
move_uploaded_file($_FILES["product_picture"]["tmp_name"],$target_file);
}
else{
$qry = "Update table_product Set product_name='$product_name', product_price='$product_price' Where product_id='$product_id'";
}
$qry_update = mysqli_query($con,$qry);
}
if(isset($_GET["delete"])){
$qry = mysqli_query($con, "Delete From table_product Where product_id='".$_GET["delete"]."'" );
if($qry){
#unlink("picture/".$_GET["picture"]);
}
}
else if(isset($_GET["edit"])){
$qry = mysqli_query($con,"Select * From table_product Where product_id='".$_GET["edit"]."'");
while($row=mysqli_fetch_array($qry,MYSQLI_ASSOC)){
$vid=$row["product_id"];
$vname=$row["product_name"];
$vprice=$row["product_price"];
}
}
?>
<!DOCTYPE html>
<html>
<head>
<title>Product</title>
</head>
<body>
<form action='<?php echo $_SERVER["PHP_SELF"]; ?>' method="post" enctype="multipart/form-data" >
<table>
<tr>
<td>Product ID</td>
<td><input type="text" name="product_id" value="<?php echo $vid;?>"></td></tr>
<tr><td>Product Name</td>
<td><input type="text" name="product_name" value="<?php echo $vname;?>"></td></tr>
<tr><td>Product Price</td>
<td><input type="text" name="product_price" value="<?php echo $vprice;?>"></td></tr>
<tr><td>Product Picture</td>
<td><input type="file" name="product_picture"></td></tr>
<tr><td colspan="2">
<input type="submit" name="button_add" value="Add">
<input type="submit" name="button_edit" value="Edit"></td></tr> </table>
</form>
<table border=1>
<tr><th>product ID</th><th>product Name</th>
<th>product price</th><th>product image</th> <th>Action</th></tr>
<?php
$qry =mysqli_query($con, "Select * From table_product");
while($row=mysqli_fetch_array($qry,MYSQLI_ASSOC)){
echo '<tr><td>'.$row["product_id"].'</td>';
echo '<td>'.$row["product_name"].'</td>';
echo '<td>'.$row["product_price"].'</td>';
echo '<td><img src="picture/'.$row["product_picture"].'" style=width:100px;height:xpx;"/></td>';
echo '<td>Edit |Delete</td></tr>';
}
?>
</table>
<br><br><br>
</body>
</html>
What is happening is when you edit only the text, the query called also updates the image path but since you don`t add an image it will be NULL.
One way is to build a conditional query inside the edit click
if(isset($_FILES["product_picture"]["name"]))
{
$product_picture = $_FILES["product_picture"]["name"];
$sql = "Update table_product Set product_name='$product_name', product_price='$product_price', product_picture='$product_picture' Where product_id='$product_id'";
target_dir = "picture/";
$target_file = $target_dir . basename($_FILES["product_picture"]["name"]);
$imageFileType = pathinfo($target_file,PATHINFO_EXTENSION);
move_uploaded_file($_FILES["product_picture"]["tmp_name"],$target_file);
}
else{
$sql = "Update table_product Set product_name='$product_name', product_price='$product_price' Where product_id='$product_id'"
}
qry = mysqli_query($con,$sql);

How to have a multiple upload in PHP?

if(isset($_POST['upload'])){
$name = $_POST['name'];
$album_id = $_POST['album'];
$file = $_FILES['file']['name'];
$file_type = $_FILES['file']['type'];
$file_size = $_FILES['file']['size'];
$file_tmp = $_FILES['file']['tmp_name'];
$random_name = rand();
if(empty($name) or empty($file)) {
echo "Please Fill all the Fields ! <br /><br />";
} else {
move_uploaded_file$file_tmp, 'uploads/'.$random_name.'.jpg');
mysql_query("INSERT INTO photos VALUE('', '$name', '$album_id', '$random_name.jpg')");
echo "Photo Uploaded !! <br /><br />";
}
}
This is how i managed to do it hope this helps
<?
function openDB()
{
global $conn, $username,$host,$password,$db;
$host = "localhost";
$username ="username";
$password= "password";
$db = "databasename";
$conn = mysql_connect($host, $username,$password) or die(mysql_error());
mysql_select_db($db,$conn) or die(mysql_error());
}
function closeDB()
{
global $conn;
mysql_close($conn);
}
?>
<form action="<? echo $_SERVER[PHP_SELF];?>" method="post" enctype="multipart/form-data">
<table>
<tr>
<td align="left"><b>Product Image:</b></td>
<td><input type="file" accept="image/*" name="product_image" size="60">
</td>
</tr>
<tr>
<td align="left"><b>Product File1:</b></td>
<td><input type="file" accept="*/*" name="product_support_file" size="60">
</td>
</tr>
<tr>
<td align="left"><b>Product File2:</b></td>
<td><input type="file" accept="*/*" name="product_support_file2" size="60">
</td>
</tr>
<tr>
<td align="left"><b>Product Price:</b></td>
<td><input type="text" name="product_price" size="60" required></td>
</tr>
<tr>
<td colspan="7" align="right"><input type="submit" name="insert_product" value="Insert Product Now"></td></tr>
</table>
</form>
<?
openDB();
$product_id = $_POST['product_id'];
$product_title = $_POST['product_title'];
$product_cat = $_POST['product_cat'];
$product_type = $_POST['product_type'];
$product_price = $_POST['product_price'];
$product_desc = $_POST['product_desc'];
$product_keywords = $_POST['product_keywords'];
$product_link = $_POST['product_link'];
//getting the image from the feild
$product_image = $_FILES['product_image']['name'];
$product_image_tmp = $_FILES['product_image']['tmp'];
$product_support_file = $_FILES['product_support_file']['name'];
$product_support_file_tmp = $_FILES['product_support_file']['tmp'];
$product_support_file2 = $_FILES['product_support_file2']['name'];
$product_support_file2_tmp = $_FILES['product_support_file2']['tmp'];
if(isset($_POST['insert_product']))
{
//gets the Text Feild Data
$insert_product = "insert into products(product_id,product_cat, product_type, product_title,
product_price, product_desc, product_image, product_support_file, product_support_file2, product_keywords,product_link)
values('','$product_cat','$product_type','$product_title',
'$product_price','$product_desc','$product_image','$product_support_file','$product_support_file2','$product_keywords','$product_link')";
if(mysql_query($insert_product))
{
//echo "
//Please enter the file path you wish to add your image to:
//<br><input type='text' name='' value=''></input>";
$file_directory ="../yourdirectory";
foreach($_FILES as $file_name => $file_array)
{
if(is_uploaded_file($file_array["tmp_name"]))
{
move_uploaded_file($file_array["tmp_name"],"$file_directory/"
.$file_array["name"]) or die ("Could not copy");
}
}
echo"<script language='Javascript'>window.open('ConformationUpload.php');</script>";
}
else{
echo"Product adding has been unsuccessfull<b>",mysql_error(),"</b>";
}
closeDB();
}
?>

How to update data of selected product?

I have a list of my products in my online ordering system and I want to update the data of the selected product. What happens is when I click the Edit link, it will just post the values from the database to other page(Edit page) and the database will not update even if I already change a data.
ADMIN.PHP (Page where all the products are listed)
<a href=addprod.php?id='.$row['ID'].'>EDIT</a>
ADDPROD.PHP (Page where the admin can add/update the product)
echo'<form method="post" action="saveprod.php" class="product" style="margin-top:500px;" enctype="multipart/form-data">';
if (isset($_GET['id'])) {
include('db.php');
$id=$_GET['id'];
$result = mysql_query("SELECT * FROM products WHERE ID = $id");
echo'<input type="hidden" name="hiddenId" value="'.$id.'">
<table border="1" cellpadding="8px" width="100%">';
while($row3 = mysql_fetch_array($result)) {
$ID = $row3['ID'];
$Image = $row3['Image'];
$Product = $row3['Product'];
$Description = $row3['Description'];
$PricePack = $row3['PricePack'];
$PriceBox = $row3['PriceBox'];
$Discount = $row3['Discount'];
$Category = $row3['Category'];
}
echo'
<tr><td align="right">Image</td><td><input type="text" id="img" name="img" value="'.$Image.'"/> </td></tr>
<tr><td align="right"></td><td><input type="file" id="img" name="img" /></td </tr>
<tr><td align="right">Product</td><td><input type="text" id="prod" name="prod" value="'.$Product.'"/></td></tr>
<tr><td align="right">Description</td><td><textarea id="desc" name="desc" style="resize:none; height:100px; width:200px; ">'.$Description.'</textarea></td></tr>
<tr><td align="right">Price Pack</td><td><input type="text" id="pck" name="pck" value="'.$PricePack.'"/></td></tr>
<tr><td align="right">Price Box</td><td><input type="text" id="box" name="box" value="'.$PriceBox.'"/></td></tr>
<tr><td align="right">Discount</td><td><input type="text" id="disc" name="disc" value="'.$Discount.'"/></td></tr>
<tr><td align="right">Category</td><td><input type="text" id="cat" name="cat" value="'.$Category.'"/></td></tr>
<tr><td align="right"></td><td><input type="submit" value="Save"/></a> <input type="reset" value="Clear"/></td></tr>';
}
echo' </table> </form>';
SAVEPROD.PHP
<?php
include('db.php');
$id = $_POST['ID'];
$Image = $_POST['Image'];
$Product = $_POST['Product'];
$Description = $_POST['Description'];
$PricePack = $_POST['PricePack'];
$PriceBox = $_POST['PriceBox'];
$Discount = $_POST['Discount'];
$Category = $_POST['Category'];
mysql_query("UPDATE products SET Image='$Image', Product='$Product', Description='$Description', PricePack='$PricePack', PriceBox='$PriceBox', Discount='$Discount', Category='$Category' WHERE ID='$id'");
header("location: admin.php");
exit();
?>
Note:
Your post data name is incorrect.
Make sure that the column name, table name you have provided is correct. Be CASE SENSITIVE about it.
You should consider mysqli_* prepared statement at least to prevent SQL injections.
Your savepro.php should look like this:
<?php
include('db.php');
/* CHANGED THE WAY YOU CALL THE POST DATA BASED FROM YOUR HTML FORM */
$id = $_POST['hiddenId'];
$Image = $_POST['img'];
$Product = $_POST['prod'];
$Description = $_POST['desc'];
$PricePack = $_POST['pck'];
$PriceBox = $_POST['box'];
$Discount = $_POST['disc'];
$Category = $_POST['cat'];
mysql_query("UPDATE products SET Image='$Image', Product='$Product', Description='$Description', PricePack='$PricePack', PriceBox='$PriceBox', Discount='$Discount', Category='$Category' WHERE ID='$id'");
header("location: admin.php");
exit();
?>
If you did it in prepared statement, it would look like the one below. So you won't worry much about SQL injections. Just a simple sample:
$stmt = $YourConnection->prepare("UPDATE products SET Image=?, Product=?, Description=?, PricePack=?, PriceBox=?, Discount=?, Category=? WHERE ID=?");
$stmt->bind_param('sssssssi', $_POST["img"], $_POST["prod"], $_POST["desc"], $_POST["pck"], $_POST["box"], $_POST["disc"], $_POST["cat"], $_POST["hiddenId"]);
$stmt->execute();
On your saveprod.php you are trying to get the value of a non-existing element, check the name of each input field on your addprod.php, it should correspond on the request you are making on your saveprod.php
Here is an example of what you are doing:
ADDPROD.PHP
<input type="text" id="img" name="img" value="'.$Image.'"/>
SAVEPROD.PHP
$Image = $_POST['Image'];
Should be this way:
ADDPROD.PHP
<input type="text" id="img" name="img" value="'.$Image.'"/>
SAVEPROD.PHP
$Image = $_POST['img'];

Categories