I wasn't sure what else to call the title...I have a PHP page that accesses a certain MySQL database, pulls the values from the table, and places them in an HTML form (POST method - PHP_SELF). The user can then view the values, alter them as they wish, and submit them. The page then takes those values and updates the MySQL database. Everything works perfectly except that when the user submits and the page goes to show the new updated variables, it still shows the old values. The user is forced refresh the page before the new variables show up. I thought that PHP was perhaps not deleting the variables, so I unset all stored variables after the script was over and it's still not working. I ever tried putting a sleep timer before the script started, and that didn't work either. I'd appreciate any suggestions. Here is my script just for reference:
<html>
<body>
<?php
$sql = "SELECT * FROM lease";
$result = mysql_query($sql);
?>
<form id="lease_update" method="post" action="<?php echo htmlentities($PHP_SELF); ?>">
<table>
<tr>
<th>Account</th>
<th>Car Lease</th>
<th>Radio Lease</th>
<th>Misc. Charges</th>
</tr>
<?php
while($rows = mysql_fetch_array($result)){
?>
<tr>
<td><input type="text" name="account[]" value="<?php echo $rows['accnt']; ?>" /></td>
<td><input type="int" name="car_lease[]" value="<?php echo $rows['car']; ?>" /></td>
<td><input type="int" name="radio_lease[]" value="<?php echo $rows['radio']; ?>" /> </td>
<td><input type="int" name="misc_lease[]" value="<?php echo $rows['misc']; ?>" /></td>
<input type="hidden" name="lease_ID[]" value="<?php echo $rows['ID']; ?>" />
</tr>
<?php
}
?>
</table>
<input type="submit" value="Update" name="lease_update" />
<?php
if(isset($_POST['lease_update'])){
$account = $_POST['account'];
$car_lease = $_POST['car_lease'];
$radio_lease = $_POST['radio_lease'];
$misc_lease = $_POST['misc_lease'];
$lease_ID = $_POST['lease_ID'];
//Get Array Lengths For Each Section
$A = count($lease_ID);
//Update Lease Information
$i = 0;
while($i < $A){
if(!mysql_query('UPDATE lease SET accnt = "' .$account[$i]. '", car = "' .$car_lease[$i]. '", radio = "' .$radio_lease[$i]. '", misc = "' .$misc_lease[$i]. '" WHERE ID = ' .$lease_ID[$i]))
die('Error: ' .mysql_error());
$i++;
}
unset($_POST);
unset($rows);
unset(result);
}
?>
</body>
</html>
You are displaying the data from the database before you update it.
It is normally good practice to do all your database connectivity at the top of the page, then display the results.
In your code (even if a user has submitted an update), you query the data, pull it from database and display it, then run the update with what the user submitted.
Changing your code to this should do the trick (Do read the note below though):
<html>
<body>
<?php
if(isset($_POST['lease_update'])){
$account = $_POST['account'];
$car_lease = $_POST['car_lease'];
$radio_lease = $_POST['radio_lease'];
$misc_lease = $_POST['misc_lease'];
$lease_ID = $_POST['lease_ID'];
//Get Array Lengths For Each Section
$A = count($lease_ID);
//Update Lease Information
$i = 0;
while($i < $A){
if(!mysql_query('UPDATE lease SET accnt = "' .$account[$i]. '", car = "' .$car_lease[$i]. '", radio = "' .$radio_lease[$i]. '", misc = "' .$misc_lease[$i]. '" WHERE ID = ' .$lease_ID[$i]))
die('Error: ' .mysql_error());
$i++;
}
unset($_POST);
unset($rows);
unset(result);
}
$sql = "SELECT * FROM lease";
$result = mysql_query($sql);
?>
<form id="lease_update" method="post" action="<?php echo htmlentities($PHP_SELF); ?>">
<table>
<tr>
<th>Account</th>
<th>Car Lease</th>
<th>Radio Lease</th>
<th>Misc. Charges</th>
</tr>
<?php
while($rows = mysql_fetch_array($result)){
?>
<tr>
<td><input type="text" name="account[]" value="<?php echo $rows['accnt']; ?>" /></td>
<td><input type="int" name="car_lease[]" value="<?php echo $rows['car']; ?>" /></td>
<td><input type="int" name="radio_lease[]" value="<?php echo $rows['radio']; ?>" /> </td>
<td><input type="int" name="misc_lease[]" value="<?php echo $rows['misc']; ?>" /></td>
<input type="hidden" name="lease_ID[]" value="<?php echo $rows['ID']; ?>" />
</tr>
<?php
}
?>
</table>
<input type="submit" value="Update" name="lease_update" />
</body>
</html>
Bad note - your code is wide open to injection attacks. You are using form data with no verification. That's a big red flag. Secondly, you are using deprecated mysql_* functions. Your code should be using mysqli_* functions or better yet move to PDO. It is much safer and you will be able to do a lot more with it.
Edit 2: The page IS being updated after the user submits the form, but the page you display to the user is querying the database before you update it - and using that to display the page to the user.
Related
enter image description hereI'm new to PHP so please don't judge :D
I'm trying to make table with edit option. No matter in which row I click "Edit" button, only data from last row of the page gets loaded. What should I do?
$sql = "SELECT * FROM countries LIMIT " . $this_page_first_result . ',' . $results_per_page;
$result = $connection-> query($sql);
echo '<div style="text-align:center; font-weight: bold;">';
for ($page=1; $page<=$num_of_pages; $page++){
echo '' . $page . ' ';
}
echo '<div><br>';
if($result-> num_rows > 0){
while($row = mysqli_fetch_assoc($result)){
$id = $row['id'];
$Name = $row['Name'];
$Area = $row['Area'];
$Population = $row["Population"];
$Phone_code = $row["Phone_code"];
echo "<tr><td><a href='cities.php?id={$row['id']}'>".$row['Name']."</a></td><td>". $row["Area"] ."</td><td>"
. $row["Population"] ."</td><td>". $row["Phone_code"] ."</td><td><button id='update-button' onclick='openEdit()'>Update</button></td><td><button id='delete-button'>Delete</button></td></tr>";
}
print_r($row);
}
else{
echo "</table><h2 style='text-align:center'>There are no countries in the database..</h2>";
}
$connection-> close();
?>
</table>
<br>
<div style="text-align:center">
<button type="button" id="close-button-edit" onclick="closeEdit()" style="display:none">Close</button>
<div id="edit_form" style="display:none; text-align:left">
<form action="edit_country.php" method="POST" class="forms">
<input type="hidden" name="id" value="<?php echo $id; ?>">
<p>Name: <input type="text" name="name" required value="<?php echo $Name; ?>"></p>
<p>Area: <input type="text" name="area" required value="<?php echo $Area; ?>"></p>
<p>Population: <input type="text" name="population" required value="<?php echo $Population; ?>"></p>
<p>Phone code: <input type="text" name="phone_code" required value="<?php echo $Phone_code; ?>"></p>
<input type="submit" name="update" value="Update">
</form>
</div>
There are two strategies that can be used for this problem: all php or using JavaScript.
PHP Only
This requires a submission to pre-fill the edit form. Each update button sends the id as a GET request (it is requesting information, not changing information, so use GET), in the form of an ordinary link, which the php script uses to populate the edit form.
<?php
// always start with php stuff and don't issue any html until you're done
// initialization
$sortDirection = 'asc';
if(isset($_REQUEST['sortDirection'])) {
// this decouples the value from user input. It can only be 'Asc' or 'Desc'
$sortDirection = $_REQUEST['sortDirection'] == 'asc' ? 'Asc' : 'desc';
}
$rowToEdit = '';
$pdo = new PDO( ... );
// Using PDO because it is more standard
// Leaving connection details to user. See https://phpdelusions.net/pdo_examples/connect_to_mysql for tutorial
// $pdo is assumed to be the pdo object
// deal with row delete. Destructive, so will be post, and delete button will be set
if(isset ($_POST['delete']) ) {
// delete from countries where id = ?
//redirect back to self (Post, Redirect, Get pattern).
// Always do this when done working with POST submissions!
header('Location: /countries.php');
exit;
}
// deal with row update. This changes data, so use POST
if(isset($_POST['id'])) {
// update countries set ...
// redirect back to self
header('Location: /countries.php');
exit;
}
// deal with request for row to edit, use GET for info requests
if(array_key_exists('id', $_GET) {
$rowToEdit = $pdo->prepare("select * from countries where id = ?");
$rowToEdit->execute([$id]);
// fall through to show page
}
// get all country rows (Note, OK to use $sortDirection here because it is decoupled from user input)
$country = $pdo->query("SELECT * FROM countries ORDER BY NAME $sortDirection")->fetchAll(PDO::FETCH_GROUP);
// got all our data, dealt with user input, now we can present the view
?>
<html>
<head>
</head>
<body>
<h1>Countries</h1>
Sort Asc
Sort Desc
<table>
<tr>
<th>Name</th>
<th>Area</th>
<th>Population</th>
<th>Phone</th>
<th></th>
<th></th>
</tr>
<?php foreach( $country as $row): ?>
<tr>
<td><a href='cities.php?country_id=<?=$row['id']?>'><?=$row['Name']?></a></td>
<td><?=$row["Area"]?></td>
<td><?=$row["Population"]?></td>
<td><?=$row["Phone_code"]?></td>
<td> <a href='countries.php?id=<?=$row['id']?>'>Update</a> </td>
<td>
<form method="post">
<input type="hidden" name="id" value="<?=$row['id']?>" />
<button id='delete-button'>Delete</button>
</form>
</td>
</tr>
</table>
<?php if($rowToEdit): ?>
<div style="text-align:center">
<form action="countries.php" method="POST" class="forms">
<input type="hidden" name="id" value="<?= rowToEdit ['id']?>">
<input type="hidden" name="sortDirection" value="<?= $sortDirection?>">
<p>Name: <input type="text" name="name" required value="<?= $rowToEdit['Name']?>"></p>
<p>Area: <input type="text" name="area" required value="<?= $rowToEdit['Area']?>"></p>
<p>Population: <input type="text" name="population" required value="<?= $rowToEdit["Population"]?>"></p>
<p>Phone code: <input type="text" name="phone_code" required value="<?= $rowToEdit["Phone_code"]?>"></p>
<input type="submit" name="update" value="Update">
</form>
</div>
<?php endif; ?>
</body>
</html>
Good afternoon,
I am building a journal, in which I have separate divs.
Each div element displays a different log, with data specific to each log in the div.
For each of the logs, I have a submit button that allows the form to be updated and edited.
What is happening, is that when I submit the form, it is updating each entry in my database, rather than just 1 single entry.
I know that the trouble is with my foreach loop, but I am unsure how to remedy this.
Any assistance or pointers would be greatly appreciated.
Code below:
<?php
$sqlGrow = "SELECT * FROM grow_details ";
$query = $conn->query($sqlGrow);
$grows = array();
while ($grow = mysqli_fetch_assoc($query) ) {
$grows[] = $grow;
}
foreach($grows as $grow) {
$id = $grow['id'];
$growName = $grow['name'];
?>
<div class="container">
<div class="details">
<h2><?php echo $grow['name']; ?></h2>
<p class="growNum">Grow #: <?php echo $id; ?></p>
<table class="growDetails">
<form method="POST" action="">
<tr>
<td class="label_growDetails"><label for="datePlanted">Date Planted:</label></td>
<td><input type="text" name="edit_datePlanted" id="edit_datePlanted" value="<?php echo $grow['datePlanted']; ?>" />
</tr>
<tr>
<td class="label_growDetails"><label for="strain">Strain:</label></td>
<td><input type="text" name="edit_strain" id="edit_strain" value="<?php echo $grow['strain']; ?>" /></td>
</tr>
<tr>
<td class="label_growDetails"><label for="toMaturity">Days to mature:</label></td>
<td><input type="text" name="edit_toMaturity" id="edit_toMaturity" value="<?php echo $grow['toMaturity']; ?>" /></td>
</tr>
<tr>
<td class="label_growDetails"><label for="type">Type:</label></td>
<td><input type="text" name="edit_type" id="edit_type" value="<?php echo $grow['type']; ?>" /></td>
</tr>
<tr>
<td class="label_growDetails"><label for="gender">Gender:</label></td>
<td><input type="text" name="edit_gender" id="edit_gender" value="<?php echo $grow['gender']; ?>" /></td>
</tr>
<tr>
<td class="label_growDetails"><label for="medium">Medium:</label></td>
<td><input type="text" name="edit_medium" id="edit_medium" value="<?php echo $grow['medium']; ?>" /></td>
</tr>
<tr>
<td class="label_growDetails"><label for="watts">Watts:</label></td>
<td><input type="text" name="edit_watts" id="edit_watts" value="<?php echo $grow['watts']; ?>" /></td>
</tr>
<tr>
<td class="label_growDetails"><label for="lightType">Light Type:</label></td>
<td><input type="text" name="edit_lightType" id="edit_lightType" value="<?php echo $grow['lightType']; ?>" /></td>
<td class="edit"><input type="submit" name="submit_editGrowDetails" id="submit_editGrowDetails" value=" Save Edits " /></td>
</tr>
</form>
</table>
</div>
And the PHP for the submit button:
<?php
if(isset($_POST['submit_editGrowDetails'])){
$edit_datePlanted = mysqli_real_escape_string($conn, $_POST['edit_datePlanted']);
$edit_strain = mysqli_real_escape_string($conn, $_POST['edit_strain']);
$edit_toMaturity = mysqli_real_escape_string($conn, $_POST['edit_toMaturity']);
$edit_type = mysqli_real_escape_string($conn, $_POST['edit_type']);
$edit_gender = mysqli_real_escape_string($conn, $_POST['edit_gender']);
$edit_medium = mysqli_real_escape_string($conn, $_POST['edit_medium']);
$edit_watts = mysqli_real_escape_string($conn, $_POST['edit_watts']);
$edit_lightType = mysqli_real_escape_string($conn, $_POST['edit_lightType']);
$name = $grow['name'];
$edit_growDetails = "UPDATE grow_details
SET datePlanted = '$edit_datePlanted',
strain = '$edit_strain',
toMaturity = '$edit_toMaturity',
type = '$edit_type',
gender = '$edit_gender',
medium = '$edit_medium',
watts = '$edit_watts',
lightType = '$edit_lightType'
WHERE name = '$name'; ";
$query_edit_growDetails = $conn->query($edit_growDetails);
if($query_edit_growDetails) {
echo '<p class="success" id="success">Successfully updated log for '.$name.'! <a class="refresh" href="journal.php">Refresh</a></p>';
} else {
echo '<p class="error" id="error">There was an error: '. $conn->error .'</p>';
}
}
?>
You should always update by the ID of the table, not the name because some may have the same name.
Let's say you have:
ID | Name
1 | Test 1
2 | Test 2
3 | Test 1
With the update query you have now, if you update "Test 1", it will update both "Test 1" with ID 1 and 3.
To fix this, on you html form, you should put a hidden field under the form like so:
<form method="POST" action="">
<input type="hidden" value="<?php echo $grow['id']; ?>" name="edit_id">
...
...
rest of code
This will echo out the id of the item you are editing.
Then on you php side, you should do this:
<?php
if(isset($_POST['submit_editGrowDetails'])){
$edit_datePlanted = mysqli_real_escape_string($conn, $_POST['edit_datePlanted']);
$edit_strain = mysqli_real_escape_string($conn, $_POST['edit_strain']);
$edit_toMaturity = mysqli_real_escape_string($conn, $_POST['edit_toMaturity']);
$edit_type = mysqli_real_escape_string($conn, $_POST['edit_type']);
$edit_gender = mysqli_real_escape_string($conn, $_POST['edit_gender']);
$edit_medium = mysqli_real_escape_string($conn, $_POST['edit_medium']);
$edit_watts = mysqli_real_escape_string($conn, $_POST['edit_watts']);
$edit_lightType = mysqli_real_escape_string($conn, $_POST['edit_lightType']);
$id = mysqli_real_escape_string($conn, $_POST['edit_id']);
$name = $grow['name'];
$edit_growDetails = "UPDATE grow_details
SET datePlanted = '$edit_datePlanted',
strain = '$edit_strain',
toMaturity = '$edit_toMaturity',
type = '$edit_type',
gender = '$edit_gender',
medium = '$edit_medium',
watts = '$edit_watts',
lightType = '$edit_lightType'
WHERE id = '$id'; ";
$query_edit_growDetails = $conn->query($edit_growDetails);
if($query_edit_growDetails) {
echo '<p class="success" id="success">Successfully updated log for '.$name.'! <a class="refresh" href="journal.php">Refresh</a></p>';
} else {
echo '<p class="error" id="error">There was an error: '. $conn->error .'</p>';
}
}
?>
I think your problem is with the following line in your submit handler:
$name = $grow['name'];
Where this $grow is referenced from i cannot see, but you should add the name in as a hidden input in your form. That way the handler knows which tuple to update. For example:
<input type="hidden" value="<?php echo $grow['name']; ?>" name="grow_name">
You can then access it via like any other piece of data from the form, i.e.
$name = mysqli_real_escape_string($conn, $_POST['grow_name']);
Some more advice:
Instead of using raw queries, you should use prepared statements with parameters, they are much safer.
Instead of updating by name, update by id. Even if the name is also unique. An id will generally have a primary key index making the query a lot faster.
The fact that the code actually updated all the entries in the database indicates to me that your handler is actually inside the for loop, that is definitely not what you want, move it out of the. With this update it will work, but if you don't move it out of the loop, it will launch a query for each tuple.
Finally #Carlos, #Riggsfolly, i'm not trying to copy your answers. Just thought i could structure the answer better.
im currently displaying all the information from the table product in a tabular format, i have a button ADD which when click should add only the id, name and price from the table product to the table product_add in the same database. but my problem is that when i click on the button ADD, nothing is entered in the product_add table.
<?php
include'connect.php';
$image =$_GET['image'];
$id =$_GET['id'];
$name =$_GET['name'];
$price=$_GET['price'];
$sql="SELECT * FROM product";
$result = mysql_query($sql);
if($result>0)
{
?>
<form method="post" id="form" name="form">
<table border='1'>
<?php
while ($row = mysql_fetch_array($result))
{
extract($row);
?>
<tr>
<td><?php echo $row['id']?></td>
<td><img src=<?php echo $row['image'] ?> /></td>
<td><?php echo $row['name']?></td>
<td><?php echo $row['price']?></td>
<td><input type='button' value='ADD' id="insert" name="insert"/></td>
</tr>
<?php
}
?>
</table>
</form>
<?php
}
if(isset($_REQUEST['insert']))
{
$insert = "INSERT INTO product_add(id, name, price)
VALUES ('$row[id]','$row['name']','$row['price']')";
$insertQuery=mysql_query($insert);
}
?>
</body>
</html>
I have updated the codes as shown below but the last row from the table product is being added to the table product_add. I want to add only a specific row when i click on the button submit.
<?php
include'connect.php';
$image = isset($_GET['image']) ? $_GET['image'] : "";
$id = isset($_GET['id']) ? $_GET['id'] : "";
$name = isset($_GET['name']) ? $_GET['name'] : "";
$price= isset($_GET['price']) ? $_GET['price'] : "";
$sql="SELECT * FROM product";
$result = mysql_query($sql);
if($result>0){
?>
<form method="POST" id="form" name="form">
<table border='1'>
<tr>
<th>Id</th>
<th>Image</th>
<th>Name</th>
<th>Price MUR</th>
</tr>
<?php
while ($row = mysql_fetch_array($result)){
extract($row);
?>
<tr>
<td><input name="id" value="<?php echo htmlspecialchars($row['id']); ?>">
</td>
<td><img src=<?php echo $row['image'] ?> width='120' height='100'/></td>
<td><input name="name" value="<?php echo htmlspecialchars($row['name']);
?>"></td>
<td><input name="price" value="<?php echo htmlspecialchars($row['price']);
?>"></td>
<td>
<input id="submit" type="submit" name="submit" value='Add to cart' />
</td>
</tr>
<?php
}
?>
</table>
</form>
<?php
}
if (isset($_REQUEST['submit']))
{
$insert = "INSERT INTO product_add(id, name, price) VALUES ('$id',
'$name','$price')";
$insertQuery=mysql_query($insert);
}
?>
Apart from the method (if your form uses POST, you should use $_POST in php), you do not have any form fields.
For example:
<?php echo $row['id']?>
Should be something like:
<input type="hidden" name="id" value="<?php echo $row['id']; ?>">
and:
<?php echo $row['name']?>
should be:
<input name="name" value="<?php echo htmlspecialchars($row['name']); ?>">
etc.
You should also switch to PDO or mysqli and prepared statements as the code you have now is vulnerable to sql injection. And ID's in html need to be unique.
One point is, you have multiple
<input type='button' ...>
with the same id="insert". ids must be unique within a web page.
The other thing is, you need a submit input to send the form
<input type="submit" ...>
From Submit Button state (type=submit)
The input element represents a button that, when activated, submits the form.
With <input type='button' ...> nothing happens, because it has no default action, see Button state (type=button)
The input element represents a button with no default behavior.
If you want an <input type='button' ...> to submit the form, you must do so by using some Javascript code.
One idea is to load content once the button is clicked.
js
$("#button").click(function() {
$("#holder").load("insert.php");
});
insert.php
$db->query("INSERT INTO table VALUES('one','two','three')");
I'm tryng to save an array so I have the following code:
<?php
$sql = "SELECT * FROM scenarii where code_s='".mysql_real_escape_string($_POST['code_s'])."'";
$qry = mysql_query($sql) or die(__LINE__.mysql_error().$sql);
$i = -1; // index des enregistrements
?>
<table cellpadding="5" cellspacing="5">
<tr>
<td><strong>CODE SCENARIO</strong></td>
<td><strong>LIBELLE</strong></td>
<td><strong>ACTION</strong></td>
<td><strong>DESCRIPTION</strong></td>
<td><strong>DATE</strong></td>
</tr>
<form action="<?php echo (isset($_POST['go'])) ? 'go.php' : '#'; ?>" method="post">
<input type="hidden" name="liasse" value="<?php echo $_POST['liasse']; ?>"/>
<input type="hidden" name="n_doss" value="<?php echo $_POST['n_doss']; ?>"/>
<input type="hidden" name="qualite" value="<?php echo $_POST['qualite']; ?>"/>
<?php while($row = mysql_fetch_assoc($qry)): ?>
<tr>
<td><input name="data[<?php echo ++$i; ?>][code_s]" type="text" value="<?php echo $row['code_s'];?>" size="10"></td>
<td><input name="data[<?php echo $i; ?>][titre]" type="text" value="<?php echo $row['titre']; ?>" size="45"></td>
<td><input name="data[<?php echo $i; ?>][action]" type="text" value="<?php echo $row['action']; ?>" size="15"></td>
<td><input name="data[<?php echo $i; ?>][libelle]" type="text" value="<?php echo $row['libelle']; ?>" size="55"></td>
<td><input type="text" name="data[<?php echo $i; ?>][date]" value="<?php echo $get_date($row['jour']) ; ?>" size="12"></td>
</tr>
<?php endwhile; ?>
And in order to save this I have this code:
if (isset($_POST['liasse'])) {
$value = $_POST['data'] ;
foreach($value as $key => $array)
{
$sql = 'INSERT INTO agenda SET
liasse = "'.mysql_real_escape_string($_POST['liasse']).'",
code_s = "'.mysql_real_escape_string($array['code_s']).'",
date_action = "'.date('Y-m-d',strtotime($array['date'])).'",
libelle = "'.mysql_real_escape_string($array['titre']).'",
action = "'.mysql_real_escape_string($array['action']).'",
description = "'.mysql_real_escape_string($array['libelle']).'",
n_doss = "'.mysql_real_escape_string($_POST['n_doss']).'",
qualite = "'.mysql_real_escape_string($_POST['qualite']).'"
';
mysql_query($sql) or die(__LINE__.mysql_error().$sql);
}
But I'm really lost,
In fact I use a form for that, now I would like to submit all of this data but without any form, directly when I have the first while I would like to save it.
The thing is that I'm lost because I can not call any var like that data[][code_s].
So I do not know how to save this. I would like to save it in background, and not to display that something has been saved.
Receive all my Utmost Respect
kind regards,
SP.
Wrap the code od the lower code block into a function and hand over the value array as argument:
function storeValues ($data) {
foreach($data as $key => $val)
{
$catalog=sprintf("%s='%s'",$key,$val);
$sql = sprintf('INSERT INTO agenda SET %s', implode(',',$catalog));
mysql_query($sql) or die(__LINE__.mysql_error().$sql);
} // foreach
} // function storeValues
You call this function when you want to save the values. So after retrieving them from the database. You call it for each row you retrieve and hand over the values like that:
storeValues ($row);
This will store one row of values at a time. Obviously this can be optimized to use a multiple insert. But let's take one step after another...
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. :)