Why unlink function will not delete old image when uploading image - php

I have to manually go into my folder every time I update an image. The image will update to a new image. However, when I update an image, the old image is not being deleted. I am using the PHP function unlink to delete the image but for some reason its not working. I have removed the at "#" sign from php unlink in the code. I have re-edited coded the code. I keep getting the following error:
Warning: unlink(picture/): Permission denied in C:\xampp\htdocs\upload_update\New_project\edit_image.php on line 24
I am trying to teach myself php, Thank you so much for your help.
This is the code:
<?php
include "connection.php";
$vid="";
$vname="";
$vprice="";
$vpicture="";
if(isset($_POST["button_edit"])){
$product_name = $_POST["product_name"];
$product_price = $_POST["product_price"];
$product_id = $_POST["product_id"];
$old_picture = $_POST['old_picture'];
if(!empty($_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);
if (isset($old_picture) && ($old_picture != $product_picture)) {
unlink("picture/" . $old_picture);
}
}
else{
$qry = "Update table_product Set product_name='$product_name', product_price='$product_price' Where product_id='$product_id'";
}
$qryUpdate = mysqli_query($con,$qry);
}
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"];
$vpicture=$row["product_picture"];
}
}
?>
<!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>
<input type="hidden" name="old_picture" value="<?php if (!empty($old_picture)) echo $old_picture; ?>" />
<tr><td>Product Picture</td>
<td><input type="file" name="product_picture" ></td></tr>
<?php if (!empty($old_picture)) {
echo '<img class="profile" src="picture/' . $old_picture . '" alt="image" style=width:150px;height:xpx;">';
} ?>
<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 </td></tr>';
}
?>
</table>
<br><br><br>
</body>
</html>

remove # sign from this line:
#unlink("picture/".$_GET["picture"])
this may show you warnings.
Use absolute path to file you want to unlink, not relative so your unlink should look like that
#unlink(__DIR__."/picture/".$_GET["picture"]);

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

PHP Image Not Coming Up [duplicate]

This question already has an answer here:
Closed 11 years ago.
Possible Duplicate:
Why isn't my image showing up?
I have a weird problem here. I have this line of code where it works on one page but it doesnt on another. The PHP code is as follows:
PHP Page That Shows Image
<table border=1>
<tr>
<td align=center>EDIT</td>
</tr>
<tr>
<td>
<table>
<?
$id = $_GET['product_id'];
$result = mysql_query("SELECT * FROM products WHERE serial = '$id'");
$info = mysql_fetch_array($result);
?>
<form method="post" action="editsuccess.php">
<input type="hidden" name="id" value="<? echo "$info[name]"?>">
<table border='0' width=100%>
<tr>
<td>Name</td>
<td>
<input type="text" name="name"
size="20" value="<? echo "$info[name]"?>">
</td>
</tr>
<tr>
<td>Description</td>
<td>
<input type="text" name="name"
size="20" value="<? echo "$info[description]"?>">
</td>
</tr>
<tr>
<td>Price</td>
<td>
<input type="text" name="address" size="40"
value="<? echo "$info[price]"?>">
</td>
</tr>
<tr>
<td>Image</td>
<td>
<? echo'<img src="../getImage.php?id=' . $info['serial'] .'"/>'?>
</td>
</tr>
<tr>
<td align="right">
<input type="submit"
name="submit value" value="Update Product">
</td>
</tr>
</form>
</table>
</td>
</tr>
</table>
PHP Page That Doesnt Show Image
<?php
$id = $_GET['product_id'];
$query = mysql_query("SELECT * FROM products WHERE serial = '$id'")
or die(mysql_error());
while($info = mysql_fetch_array($query)) {
echo "";
$name = $info['name'];
$description = $info['description'];
$price = $info['price'];
$picture = $info['picture'];
}
?>
<form action="editsuccess.php?product_id=<?php echo $id; ?>" method="post">
Product ID:<br/>
<input type="text" value="<?php echo $id;?>" name="product_id" disabled/>
<br/>
Name:<br/>
<span id="sprytextfield1">
<input type="text" value="<?php echo $name;?>" name="name"/>
<span class="textfieldRequiredMsg">Enter Product Name</span></span><br/>
Description:<br/>
<span id="sprytextfield2">
<input type="text" value="<?php echo $description;?>" name="description"/>
<span class="textfieldRequiredMsg">Enter A Description</span></span><br/>
Price:<br/>
<span id="sprytextfield3">
<input type="text" value="<?php echo $price;?>" name="price"/>
<span class="textfieldRequiredMsg">Enter Price</span><span class="textfieldInvalidFormatMsg">Enter Numbers Only</span></span><br/>
Picture:<br/>
<?php echo '<img src="../getImage.php?id=' . $row['serial'] .'"/>'
?>
</br>
<input type="submit" value="Update Product"/>
</form>
The line of code i am talking about is this one:
<?php echo '<img src="../getImage.php?id=' . $row['serial'] .'"/>'
?>
Any ideas why it dont work???
-----EDIT--------
getImage.php code is as follows:
<?php
$host="localhost"; // Host name
$user="****"; // Mysql username
$passwd="****"; // Mysql password
$dbName="**********"; // Database name
// Connect to server and select databse.
mysql_connect("$host", "$user", "$passwd")or die("cannot connect");
mysql_select_db("$dbName")or die("cannot select DB");
$link = mysql_connect($host, $user, $passwd);
mysql_select_db($dbName);
$query = 'SELECT picture FROM products WHERE serial="' . $_GET['id'] . '"';
$result = mysql_query($query,$link);
$row = mysql_fetch_assoc($result);
header("Content-type: image/jpeg");
echo $row['picture'];
?>
First of all, try to avoid short tags (<?). Not every webserver is configured to understand them and it kind of conflicts with XML tags (which open with <?xml). So replace your <? with <?php to make sure your code always works on any webserver, regardless of it's configuration setting for short_open_tags.
Second, You're calling $row['serial'], but $row doesn't appear to be an array (at least it's not defined within the code you pasted here). Are you sure it shouldn't be $info['serial']?
But most importantly, whenever you allow user-input (like a $_GET) to determine your SQL query, always escape your code with mysql_real_escape_string, like this:
$result = mysql_query("SELECT * FROM products WHERE serial = '" . mysql_real_escape_string($id) . "'");
Or when you're sure that it's always an integer (e.g. if the field has INT datatype in your database), cast the value as an integer, like so:
$result = mysql_query("SELECT * FROM products WHERE serial = " . (int) $id);
You shooed to remove while cicluse
next code
while($info = mysql_fetch_array($query)) {
echo "";
$name = $info['name'];
$description = $info['description'];
$price = $info['price'];
$picture = $info['picture'];
}
?>
change just with
$info = mysql_fetch_array($query)
Try and tell us does is ok, and does is like you want. :)

Why isn't my image showing up?

-------EDIT-------
hi guys, seeing that you solved this problem for me, i thought it would be a good idea to solve the same problem again but on a different page. i cannot get the image to show up.
<?php
$id = $_GET['product_id'];
$query = mysql_query("SELECT * FROM products WHERE serial = '$id'")
or die(mysql_error());
while($info = mysql_fetch_array($query)) {
echo "";
$name = $info['name'];
$description = $info['description'];
$price = $info['price'];
$picture = $info['picture'];
}
?>
<form action="editsuccess.php?product_id=<?php echo $id; ?>" method="post">
Product ID:<br/>
<input type="text" value="<?php echo $id;?>" name="product_id" disabled/>
<br/>
Name:<br/>
<input type="text" value="<?php echo $name;?>" name="name"/>
<br/>
Description:<br/>
<input type="text" value="<?php echo $description;?>" name="description"/>
<br/>
Price:<br/>
<input type="text" value="<?php echo $price;?>" name="price"/>
<br/>
Picture:<br/>
<? echo'<img src="../getImage.php?id=' . $info['serial'] .'"/>'?>
</br>
<input type="submit" value="Update Product"/>
</form>
This is a page where an admin can edit a product from a row in a table.
The image is not showing up for some reason.
Thanks for any suggestions.
------EDIT ENDS HERE--------
I still cannot get my PHP image to show up even after following the right method in uploading an image to the database. the following code is for displaying the image:
<form name="form1">
<input type="hidden" name="productid" />
<input type="hidden" name="command" />
</form>
<table border="0" cellpadding="2px" width="600px">
<?
$result=mysql_query("select * from products");
while($row=mysql_fetch_array($result)){
?>
<tr>
<td><?php '<img src="getImage.php?id=' . $row['serial'] .'"/>'
?>
</td>
<td> <b><?=$row['name']?></b><br />
<?=$row['description']?><br />
Price:<big style="color:green">
£<?=$row['price']?></big><br /><br />
<input type="button" value="Add to Cart" onclick="addtocart(<?=$row['serial']?>)" />
</td>
</tr>
<tr><td colspan="2"><hr size="1" /></td>
<? } ?>
</table>
the getImage.php looks like this:
...
$link = mysql_connect($host, $user, $passwd);
mysql_select_db($dbName);
$query = 'SELECT picture FROM products WHERE serial="' . $_GET['id'] . '"';
$result = mysql_query($query,$link);
$row = mysql_fetch_assoc($result);
echo $row['picture'];
?>
only the name, description and price is showing up on the webpage. my MySQL table looks like this:
serial
name
description
price
picture (blob)
You are not setting the correct Content-type header before echoing out the image data.
You MUST also escape the $_GET['id'] parameter.
// Escape $id
$id = mysql_real_escape_string($_GET['id']);
$link = mysql_connect($host, $user, $passwd);
mysql_select_db($dbName);
// Use the escaped $id
$query = "SELECT picture FROM products WHERE serial='$id'";
$result = mysql_query($query,$link);
if ($result) {
$row = mysql_fetch_assoc($result);
// Set the Content-type
// This assumes image/jpeg. If you have different image types,
// you'll need logic to supply the correct MIME type
// image/jpeg image/png image/gif, etc
header("Content-type: image/jpeg");
echo $row['picture'];
}
?>
In your main script, it looks like you are merely missing an echo
<td><?php '<img src="getImage.php?id=' . $row['serial'] .'"/>'
// Should be
<td><?php echo '<img src="getImage.php?id=' . $row['serial'] .'"/>'
// ------^^^^^^

Categories