Error in updating a mysql table - php

here I'm trying to display the record of a member and trying to edit the details.
First, I'm fetching the details from a database into textboxes, then, when I should hit the submit button..it should update the entry which is updated and should keep the original value of the textbox which is not updated.
Here's the code :-
The first one is of editmember.php
<?php
session_start();
include 'dbconnector.php';
$receivedusername=$_REQUEST['username'];
$parentusername=$_SESSION['username'];
$_SESSION['cusername']=$receivedusername;
//check session
if((isset($_SESSION['logged'])) && ($_SESSION['logged']==1))
{
//now map the user to it's parent account
$query="select * from master_member where parentusername = '" . $parentusername . "' and currentusername = '" . $receivedusername . "'";
$result=mysql_query($query,$db) or die (mysql_error($db));
if(mysql_num_rows($result) > 0)
{
$row=mysql_fetch_assoc($result);
//account mapped, green signal to proceed
?>
<form action="memberaction.php?action=edit" method="post">
<table>
<tr>
<td>Username : <input type="text" name="usrnm" value="<?php echo ($row['currentusername']); ?>" /></td>
</tr>
<tr>
<td>Email : <input type="text" name="eml" value="<?php echo ($row['currentemail']); ?>" /></td>
</tr>
<tr>
<td><input type="submit" name="submit" value="submit"></td>
</tr>
</table>
</form>
<?php
}
else
{
echo "You aren't authorized to perform this task, redirecting.";
header('refresh:2;URL=members.php');
exit();
}
}
else
{
header('Location:login.php');
exit();
}
?>
memberaction.php
case 'update':
$memberusername=$_SESSION['cusername'];//username of the member, whose account is to be edited.
$parentusername=$_SESSION['username'];//username of the parent.
//since the account is already matched to the parent account before, we do not need to do it again.
//get the field value
$usrnm=(isset($_POST['usrnm'])) ? $_POST['usrnm'] : '';
$eml=(isset($_POST['eml'])) ? $_POST['eml'] : '';
$query="update master_member set currentusername = '" . $usrnm . "' and currentemail = '" . $eml . "' where parentusername = '" . $parentusername . "' and currentusername = '" . $memberusername . "'";
$result=mysql_query($query,$db) or die (mysql_error($db));
if($result)
{
echo "updated";
header('refresh:2;URL=members.php');
exit();
}
else
{
echo "Errors";
}
break;
After I hit the submit button, it displays successfully updated, but no change takes place at the database.
What possible mistake I'm doing ?
My DB structure is like :-
http://sqlfiddle.com/#!2/969c54/2

Related

how to edit a record from MySQL database

this is my first post!
First off, I have my code which outputs a table on index.php. At the end I have an edit link which takes me to the edit.php page:
if ($result->num_rows > 0) {
echo "<p><table><tr><th>ID</th><th>Film Name</th><th>Producer</th><th>Year Published</th><th>Stock</th><th>Price</th><th>Function</th></tr>";
while($row = $result->fetch_assoc()) {
echo "<tr><td>".$row["ID"]."</td><td>".$row["FilmName"]."</td><td>".$row["Producer"]."</td><td>".$row['YearPublished']."</td><td>".$row['Stock']."</td><td>".$row['Price']."</td><td>"."Edit / Delete"."</td></tr></p>";
}
echo "</table>";
edit.php (first there is the form):
$query = "SELECT * FROM ProductManagement WHERE ID=" . $_GET["ID"] . ";"; // Place required query in a variable
$result = mysqli_query($connection, $query); // Execute query
if ($result == false) { // If query failed
echo "<p>Getting product details failed.</p>";
} else { // Query was successful
$productDetails = mysqli_fetch_array($result, MYSQLI_ASSOC); // Get results (only 1 row
// is required, and only 1 is returned due to using a primary key (id in this case) to
// get the results)
if (empty($productDetails)) { // If getting product details failed
echo "<p>No product details found.</p>"; // Display error message
}
}
?>
<form id="updateForm" name="updateForm" action="<?php echo "?mode=update&ID=" . $productDetails["ID"]; ?>" method="post">
<div>
<label for="updateFormProductCostPrice">ID</label>
<input id="updateFormProductCostPrice" name="ID" type="text" readonly
value="<?php echo $productDetails["ID"]; ?>">
</div>
<div>
<label for="updateFormProductName">Film Name</label>
<input id="updateFormProductName" name="FilmName" type="text" value="<?php echo $productDetails["FilmName"]; ?>">
</div>
<div>
<label for="updateFormProductDescription">Producer</label>
<textarea rows="4" cols="50" id="Producer"
name="productDescription"><?php echo $productDetails["Producer"]; ?></textarea>
</div>
<div>
<label for="updateFormProductPrice">Year Produced</label>
<input id="updateFormProductPrice" name="YearProduced" type="text"
value="<?php echo $productDetails["YearProduced"]; ?>">
</div>
<div>
<label for="updateFormProductStock">Stock:</label>
<input id="updateFormProductStock" name="Stock" type="text"
value="<?php echo $productDetails["Stock"]; ?>">
</div>
<div>
<label for="updateFormProductEan">Price:(&#163)</label>
<input id="updateFormProductEan" name="Price" type="text"
value="<?php echo $productDetails["Price"]; ?>">
</div>
<div>
<input id="updateSubmit" name="updateSubmit" value="Update product" type="submit">
</div>
</form>
</body>
Then there is the php code to update the record (edit.php continued):
if (((!empty($_GET["mode"])) && (!empty($_GET["id"]))) && ($_GET["mode"] == "update")) { // If update
echo "<h1>Update product</h1>";
if (isset($_POST["updateSubmit"])) { // If update form submitted
// Check all parts of the form have a value
if ((!empty($_POST["ID"])) && (!empty($_POST["FilmName"]))
&& (!empty($_POST["Producer"])) && (!empty($_POST["YearProduced"]))
&& (!empty($_POST["Stock"])) && (!empty($_POST["Price"]))) {
// Create and run update query to update product details
$query = "UPDATE products "
. "SET FilmName = '" . $_POST["FilmName"] . "', "
. "Producer = '" . $_POST["Producer"] . "', "
. "YearProduced = '" . $_POST["YearProduced"] . "', "
. "Stock = " . $_POST["Stock"] . ", "
. "Price = '" . $_POST["Price"] . "' "
. "WHERE id=" . $_GET['ID'] . ";";
$result = mysqli_query($connection, $query);
if ($result == false) { // If query failed - Updating product details failed (the update statement failed)
// Show error message
echo "<p>Updating failed.</p>";
} else{ // Updating product details was sucessful (the update statement worked)
// Show success message
echo "<p>Updated</p>";
}
}
}
}
I do apologise that there is a lot of code here. Basically when I click edit in the table on the home page, I would expect it to load up the data for the respective row selected so I can update it.
Currently, when I click the 'edit' link, it loads the edit page and it has the blank fields and says "getting product details failed". It would be great if it can retrieve the data for the respective row selected. Can someone help please? Thanks!
In edit.php file $_GET["ID"] is empty because there is no ID value in your link so query returns no results.
Also in your last file you have $_GET["id"] which is different from the value you use ($_GET["ID"]).
Try this:
echo "
<tr>
<td>".$row["ID"]."</td>
<td>".$row["FilmName"]."</td>
<td>".$row["Producer"]."</td>
<td>".$row['YearPublished']."</td>
<td>".$row['Stock']."</td>
<td>".$row['Price']."</td>
<td>Edit
<td>Delete
</tr>";
Also you are SQL Injection vulnerable. You can combine mysqli with prepared statements to avoid this.

Database not updating correctly in PHP / MySQL [duplicate]

This question already has answers here:
Can I mix MySQL APIs in PHP?
(4 answers)
Closed 7 years ago.
I've got a database with a Users table which I'm trying to update.
Currently I have customers.php, which displays form fields with the user information so it can be updated.
This form points to edit_customer_processor.php , which takes the new values, puts them into a MYSQL query... and then despite the query working correctly when I query the DB via the PHPMyAdmin command line, the record doesn't update.
customers.php
<?php
session_start();
if(!$_SESSION["logged_in"]){
header("location:home.php");
die;
}
?>
<?php include 'header.html'; ?>
<div id='maincontent'>
<?php
if (isset($_GET["id"])){
$customer_id = $_GET["id"];
require_once('config.php');
$customer_query = "SELECT * FROM customer WHERE customer_id = $customer_id";
$customer_results = mysql_query($customer_query, $conn);
if (!$customer_results) {
die ("Error selecting car data: " .mysql_error());
}
else {
while ($row = mysql_fetch_array($customer_results)) {
echo "<h3>Edit Customer</h3>";
echo "<FORM method='post' action='edit_customer_processor.php'>";
echo '<p> Name: <input type="text" name="name" size = "40" value=' . $row[name] . '></p>';
echo '<p> Address: <input type="text" name ="address" size="40" value=' . $row[address] . '></p>';
echo '<p> Email: <input type="text" name="email" value=' . $row[email] . '></p>';
echo '<p> Phone: <input type ="text" name="phone" size="20" value=' . $row[phone] . '></p>';
echo '<input type ="hidden" name="customer_id" value="' . $row[customer_id] . '">';
echo '<input type ="hidden" name="formtype" value="edit_customer">';
echo '<input type="submit" name="submit" value= "Update">';
echo '</form>';
}
}
} else {
// If there isn't an ID, display the New Customer form and all customers below, with links
// to their edit pages.
echo "<h3>Enter new customer information and submit.</h3>";
echo "<FORM method='post' action='new_customer_processor.php'>";
echo '<p> Name: <input type="text" name="name" size = "40"></p>';
echo '<p> Address: <input type="text" name ="address" size="40"></p>';
echo '<p> Email: <input type="text" name="email"></p>';
echo '<p> Phone: <input type ="text" name="phone" size="20"></p>';
echo '<input type ="hidden" name="formtype" value="new_customer">';
echo '<input type="submit" name="submit" value= "Submit">';
echo '<input type ="reset" name="reset" value ="Reset">';
echo '</form>';
require_once('config.php');
echo "<h3>Current Customers</h3>";
$query = "SELECT * FROM customer";
$results = mysql_query($query, $conn);
if (!$results) {
die ("Error selecting customer data: " .mysql_error());
}
else {
// In the absence of an ID, all customers will be displayed down
// the bottom of the page
while ($row = mysql_fetch_array($results)) {
echo "<a href=customers.php?id=";
echo $row[customer_id];
echo "><p> $row[name] </p></a>";
echo "<p> $row[address] </p>";
echo "<p> $row[phone] </p>";
echo "<p> $row[email] </p>";
}
}
}
?>
Back to Customers Page
</div>
<?php include 'footer.html' ?>
edit_customer_processor.php
<?php include 'header.html' ?>
<div id="maincontent">
<?php
// Pulling in hidden customer ID from post value
$mysqli = new mysqli( 'localhost', 'root', 'root', 'w_c_a' );
// Check our connection
if ( $mysqli->connect_error ) {
die( 'Connect Error: ' . $mysqli->connect_errno . ': ' . $mysqli->connect_error );
}
// Insert our data
$sql = mysql_query("UPDATE customer
SET name = '".mysql_real_escape_string($_POST['name'])."',
address = '".mysql_real_escape_string($_POST['address'])."',
phone = '".mysql_real_escape_string($_POST['phone'])."',
email = '".mysql_real_escape_string($_POST['email'])."'
WHERE customer_id='".mysql_real_escape_string($_POST['customer_id'])."'");
$update = $mysqli->query($sql);
echo "Customer updated: ";
echo "<a href=customers.php?id=" . $_POST['customer_id'] . ">";
echo "Back to Edit Customer</a>";
?>
</div>
<?php include 'footer.html' ?>
And when I echo the MYSQL query, I get:
UPDATE customer SET name = 'Kellyassdsa', address = 'ads', phone = '0260123123', email = 'asdasd' WHERE customer_id='1'
Which works when I put it in PHPMyAdmin.
I know it'll be some boneheaded little mistake, but I've been trying to get this work for ages now. Any ideas?
Maybe your program just can't connect to your MySQL database.
$customer_results = mysql_query($customer_query, $conn);
I can't see where you gave a value to the var $conn.
If the problem is connection problem then we might need your database info like the name of your table in PhpMyAdmin.
your problem is...
$sql = mysql_query(..);
$update = $mysqli->query($sql);
it should be
$sql = 'UPDATE ...';
$update = $mysqli->query($sql);
i think problem occurs due to line break. pleas make a query in single line without line break.
$sql = mysql_query("UPDATE customer SET name = '".mysql_real_escape_string($_POST['name'])."',address = '".mysql_real_escape_string($_POST['address'])."', phone = '".mysql_real_escape_string($_POST['phone'])."', email = '".mysql_real_escape_string($_POST['email'])."' WHERE customer_id='".mysql_real_escape_string($_POST['customer_id'])."'");
Hope this helps..

update statement with image

I have a php page with form for updating records and image I don’t know what is wrong with the update statement ,,, the values of fields are taken and I can see them on url through the GET method ... But when I run the page and update record information is not changing and nothing appear on the page ,,, since none of fields r taking the update I think my update statement having problem ,,,here is the code:
<?php
// Connect to the database
require("includes/conn.php");
// Script Variables
$target_dir = 'images/';
$file_given = false;
$inputs_given = false;
$id_given = false;
if(isset($_POST['serialid']) && $_POST['serialid'] != "")
{
$serialid = $_POST['serialid'];
$id_given = true;
}
// You only need to catch input from a create or modify action, so start by checking for ALL the REQUIRED inputs
if(isset($_POST['name']) && $_POST['name'] != "" && isset($_POST['description']) && $_POST['description'] != "" && isset($_POST['price']) && $_POST['price'] != "")
{
$name = $_POST['name'];
$paragraph = $_POST['description'];
$price = $_POST['price'];
if(isset($_POST['picture']) && $_POST['picture'] != "")
{
$picture = basename($_FILES['picture']['name']);
$file_given = true;
}
// Just some verification (not really much, but you can write your own functions and slot them in
$name_safe = true;
$description_safe = true;
$price_safe = true;
$picture_safe = false;
if($_FILES["picture"]["type"] == "image/gif" || $_FILES["picture"]["type"] == "image/jpg" || $_FILES["picture"]["type"] == "image/png" || $_FILES["picture"]["type"] == "image/bmp")
$picture_safe = true;
if($name_safe && $description_safe && $price_safe && $picture_safe)
$inputs_given = true;
}
if($id_given && $inputs_given)
{
// Search for the record and see if it exists
$get_record = mysql_query("SELECT serial, picture FROM products WHERE serial='$serialid'");
$record_exists = mysql_num_rows($get_record);
if($record_exists == 1)
{
if($file_given)
{
$update_image = ", picture='$picture'";
// Now we need to remove the old image from the file system and upload our new one in it's place
$previous_image = mysql_result($get_record,'0','picture');
unlink($target_dir . $previous_image);
//Now that the previous image has been removed, we need to upload our new image
$new_image = $target_dir . $picture ;
move_uploaded_file($_FILES['picture']['tmp_name'], $new_image);
}
else
$update_image = "";
if(mysql_query("UPDATE products SET name='$name', description='$description', price='$price', " . $update_image . " WHERE serial='$serialid'"))
$action_output = "Record successfully modified.";
else
$action_output = "Record modification unsuccessful.";
}
else
$action_output = "The record id you specified does not exist.";
}
?>
<html>
<head>
<title>Manage Records</title>
</head>
<body>
<?php echo $action_output; ?>
</body>
</html>
<?php
// Disconnect from the database
?>
Here is the url when I click the modify
http://localhost/Shopping/update.php?name=View+Sonic+LCD&description=LCD&price=250&picture=C%3A%5CDocuments+and+Settings%5Ce2565%5CMy+Documents%5CTwasul%5Ctlogo%5Cicon%5Cpic1.jpg&serialid=1
My Modify Form is this
<?php
// Connect to the database
require("includes/conn.php");
$id_given = false;
if(isset($_POST['serialid']) && $_POST['serialid'] != "")
{
$serialid = $_POST['serialid'];
$id_given = true;
}
if($id_given)
{
$get_record = mysql_query("SELECT * FROM products WHERE serial='$serialid'");
$record = mysql_fetch_array($get_record);
$output = '<form method="POST" enctype="multipart/form-data" action="update.php?serialid=' . $record['serialid'] . '&action=modify">
<table>
<tr>
<td>Name:</td>
<td><input name="name" type="text" value="' . $record['name'] . '"/></td>
</tr>
<tr>
<td>Description :</td>
<td><textarea name="description" cols="45" rows="5">' . $record['description'] . '</textarea></td>
</tr>
<tr>
<td>Price:</td>
<td><input name="price" type="text" value="' . $record['price'] . '"/></td>
</tr>
<td colspan="2"><img height="50" width="50" src="../images/' . $record['picture'] . '"/><br/>' . $record['picture'] . '</td>
</tr>
<tr>
<td>Modify Image:</td>
<td><input name="picture" type="file" value="" /></td>
</tr>
<tr>
<td colspan="2"><input type="submit" value="Modify Record"/>
</td>
</tr>
</table>
</form>';
}
else
$output = 'No record id was specified.';
?>
<html>
<head>
<title>Modify Record</title>
</head>
<body>
<?php echo $output; ?>
</body>
</html>
<?php
// Disconnect from the database
?>
First, you have an extra comma in this line, before the WHERE :
if(mysql_query("UPDATE products SET name='$name', description='$description', price='$price', " . $update_image . " WHERE serial='$serialid'"))
The correct syntax is :
if(mysql_query("UPDATE products SET name='$name', description='$description', price='$price' " . $update_image . " WHERE serial='$serialid'"))
Then, you said
I can see them on url through the GET method
But in your script you are using $_POST variable to get values, use $_GET instead or change the method of your form to post.
If you want to upload a picture you have to use post method, the file will be available in the $_FILES variable.
In your example, you pass parameters by URL so, with the get method, and the "picture" is just the path to the picture in your PC, and it's not uploaded on the server.
EDIT :
Add "<input type='hidden' name='serialid' value='".$record['serialid']."' />" AND "<input type='hidden' name='action' value='modify' />" in your form instead of add this parameters to the action url of it, and it should work
you have added comma in $update_image = ", picture='$picture'"; as well as in
if(mysql_query("UPDATE products SET name='$name', description='$description', price='$price', " . $update_image . " WHERE serial='$serialid'"))
either remove the comma in $update_image = " picture='$picture'"; or remove in this
if(mysql_query("UPDATE products SET name='$name', description='$description', price='$price' " . $update_image . " WHERE serial='$serialid'"))'

PHP trouble using $_POST in a loop

edit - I solved my "add friend" button issue, now I'm trying to get the userid from the loop below. I want to be able to get the userid of the name that the user looks up (the name that gets submitted to findUsers function, $friend). So basically I want to be able to use result['userid'] and be able to submit that into a database.
I commented in the code where I'm having trouble getting the value for the userid to set.
<input type="hidden" name="userId" value="' . $result['userid'] . '" />
Is there a certain way to use hidden inputs, or is the value just not being set correctly?
<?php
include_once 'config.php';
class Friends{
function addFriend($userId) {
return $userId; //this is supposed to return the value of the user's id selected in the loop below via the if statements towards the bottom.
}
function findUsers($friend){
$search = mysql_query("SELECT * from users where username='$friend'");
if (mysql_num_rows($search) > 0){
// $this->addFriend($friend);
$userLocation = mysql_query("select * from userinfo where username='$friend'");
$locationResult = mysql_fetch_array($userLocation);
$locationResultArray = $locationResult['userlocation'];
$locationExplode = explode("~","$locationResultArray");
if (mysql_num_rows($search)) {
// Table column names
echo '<table><tr><td>Username</td><td>Location</td></tr>';
while($result = mysql_fetch_array($search)) {
echo '<tr>
<td>'. $result['username'] . '</td>
<td>' . $locationExplode[0] . ', ' . $locationExplode[1] . '</td>
<td>
<form method="post" name="friendRequest" action="">
<input type="hidden" name="userId" value="' . $result['userid'] . '" />
<input type="submit" name="addFriend" value="Add Friend" />
</form>
</td></tr>';
}
}
}
}
}
$friends = new Friends();
if (isset($_POST['userId'], $_POST['addFriend'])) {
echo "friend button pressed"; //this message is displayed
if ($friends->addFriend($_POST['userId'])) {
echo "userID set"; //this message is displayed
echo $_POST['userID']; //this is not displayed
} else {
// some error code here
}
}
// Edit this to test here
// $friends->findUsers('<username>');
?>
That way to add friend is incorrect way, because when you click the "Add friend" button, that will send a $_POST['addFriend'] and then in the loop the check are going to add all users as friend.
The correct code is here:
<?php
function addFriend($userId){
// check is 'userId' exist, if not, then return 0;
}
if (isset($_POST['userId'], $_POST['addFriend'])) {
if (addFriend($_POST['userId'])) {
// some display code here
} else {
// some error code here
}
}
while($result = mysql_fetch_array($search)) {
?>
<tr><td>
<form method="post" name="friendRequest" action="">
<input type="hidden" name="userId" value="<?php echo $result['userid']; ?>" />
<input type="submit" name="addFriend" value="Add Friend" />
</form>
</td></tr>
<?php } ?>
EDIT1:
You can't use the code above into a function. I fixed a lot of bug that I can see in your code, but still look strange.
I don't get what you want to do with your code, but I made this:
<?php
function addFriend($userId) {
return 1; //using 1 for testing purposes
}
function findUsers($friend) {
$search = mysql_query('SELECT `userid`, `username`, `userlocation` FROM `users` JOIN `userinfo` ON `users`.`username` = `userinfo`.`username` WHERE `user`.`username` = ' . $friend);
if (mysql_num_rows($search)) {
// Table column names
echo '<table><tr><td>Username</td><td>Location</td></tr>';
while($result = mysql_fetch_array($search)) {
$locationExplode = explode('~', $result['userlocation']);
echo '<tr>
<td>'. $result['username'] . '</td>
<td>' . $locationExplode[0] . ', ' . $locationExplode[1] . '</td>
<td>
<form method="post" name="friendRequest" action="">
<input type="hidden" name="userId" value="' . $result['userid'] . '" />
<input type="submit" name="addFriend" value="Add Friend" />
</form>
</td></tr>';
}
}
}
if (isset($_POST['userId'], $_POST['addFriend'])) {
if (addFriend($_POST['userId'])) {
echo "test"; //I'm simply trying to get the input to work, can't get it to post. Just using this for a test.
} else {
// some error code here
}
}
// Edit this to test here
// findUsers('<username>');
?>
EDIT2:
Well, you just need to put my functions code into the class and then use the other code outside the class, like this:
<?php
include_once 'config.php';
class Friends{
function addFriend($userId) {
return 1; //using 1 for testing purposes
}
function findUsers($friend) {
$search = mysql_query('SELECT `userid`, `username`, `userlocation` FROM `users` JOIN `userinfo` ON `users`.`username` = `userinfo`.`username` WHERE `user`.`username` = ' . $friend);
if (mysql_num_rows($search)) {
// Table column names
echo '<table><tr><td>Username</td><td>Location</td></tr>';
while($result = mysql_fetch_array($search)) {
$locationExplode = explode('~', $result['userlocation']);
echo '<tr>
<td>'. $result['username'] . '</td>
<td>' . $locationExplode[0] . ', ' . $locationExplode[1] . '</td>
<td>
<form method="post" name="friendRequest" action="">
<input type="hidden" name="userId" value="' . $result['userid'] . '" />
<input type="submit" name="addFriend" value="Add Friend" />
</form>
</td></tr>';
}
}
}
}
$friends = new Friends();
if (isset($_POST['userId'], $_POST['addFriend'])) {
if ($friends->addFriend($_POST['userId'])) {
echo "test";
} else {
// some error code here
}
}
// Edit this to test here
// $friends->findUsers('<username>');
?>
EDIT3:
That's because the function addFriend is incorrect... You need to pass the user ID value as argument and then display it like this:
function addFriend($userId) {
return $userId; //this is supposed to return the value of the user's id selected in the loop below via the if statements towards the bottom.
}

UPDATE query on row which leaves original time intact MySQL

I have got a script under this link Order list/ while loop php issue which retrieves an order row of data from the following fields:
order_id | users_id | total | order_date(CURRENT_TIMESTAMP) | shipped
I have since added a radio button in which the admin user can click to show if this item has been shipped. (It adds a 'YES' or 'NO' to the shipped field through a submit button) The SQL query is below:
UPDATE orders SET shipped='$shipped' WHERE order_id='$id'
The script works fine but it replaces the time that the order was originally made (under 'order_date') with the time that the shipping button has been submitted and I want to leave the original time intact.
Can I change the SQL query or do I have to use php to this? Please let me know if you need to see the full php code.
<?php # edit_user.php
$page_title = 'View Individual Order';
include ('includes/header_admin_user.html');
// If no dealer_code variable exists, redirect the user.
if (!isset($_SESSION['admin_int_id'])) {
// Start defining the URL.
$url = 'http://' . $_SERVER['HTTP_HOST']
. dirname($_SERVER['PHP_SELF']);
// Check for a trailing slash.
if ((substr($url, -1) == '/') OR (substr($url, -1) == '\\') ) {
$url = substr ($url, 0, -1); // Chop off the slash.
}
// Add the page.
$url .= '/login.php';
ob_end_clean(); // Delete the buffer.
header("Location: $url");
exit(); // Quit the script.
}
// Check for a valid user ID, through GET or POST.
if ( (isset($_GET['id'])) && (is_numeric($_GET['id'])) )
{ // Accessed through view_users.php
$id = $_GET['id'];
} elseif ( (isset($_POST['id'])) && (is_numeric($_POST['id'])) )
{ // Form has been submitted.
$id = $_POST['id'];
} else { // No valid ID, kill the script.
echo '<h1 id="mainhead">Page Error</h1>
<p class="error">This page has been accessed in error.</p><p><br /><br /></p>';
include ('./includes/header.html');
exit();
}
?>
<h1>Order Details</h1>
<?php
require_once ('mydatabase.php'); // Connect to the db.
$shipped = $_POST["shipped"];
if (isset($_POST['submitted'])) {
// Make the query.
$query = "UPDATE orders SET shipped='$shipped' WHERE order_id=$id";
$result = #mysql_query ($query); // Run the query.
if (mysql_affected_rows() == 1) { // If it ran OK.
// Print a message.
echo '<p style="color:#5a8e22;"><strong>The order has been sent.</strong></p>
<br />';
} else { // If it did not run OK.
echo '<p style="color:#be0f34; font-size:120%;"><strong>Error</strong></p>
<p style="color:#be0f34;">This update request could not be made for one of the following reasons:<br>
<br>
<< Go back to order list';
echo '<p>' . mysql_error() . '<br /><br />
Query: ' . $query . '</p>
</p>
<br class="clearboth" />
<p> </p>
<p> </p>
</div>
</div>'
; // Debugging message.
include ('./includes/footer_admin_user.html');
exit();
; // Public message.
}
} // End of submit conditional.
// Retrieve the user's, order and product information.
$query = "SELECT us.users_id, us.users_sales_guild_id, us.users_first_name, us.users_surname, us.users_dealer_name, us.users_type,
us.users_address_street, us.users_address_suburb, us.users_address_state, us.users_address_postcode,
us.users_address_phone, us.registration_date,
ord.order_id, ord.users_id, ord.total, ord.order_date,
oc.oc_id, oc.order_id, oc.products_id, oc.quantity, oc.price,
prd.products_id, prd.products_name, prd.price
FROM users AS us, orders AS ord, order_contents AS oc, products AS prd
WHERE ord.order_id=$id
AND us.users_id = ord.users_id
AND ord.order_id = oc.order_id
AND oc.products_id = prd.products_id
";
$result = mysql_query ($query) or die(mysql_error());
if (mysql_num_rows($result)) { // Valid user ID, show the form.
$row = mysql_fetch_array($result, MYSQL_NUM);
echo '<table width="400" border="0" cellspacing="0" cellpadding="0">
<tr valign="top">
<td width="65%"><p><strong>Deliver to:</strong><br />
' . $row[2] . ' ' . $row[3] . ' <br />
' . $row[5] . ', ' . $row[1] . ' <br />
</p>
<p><strong>Dealership:</strong><br />
' . $row[4] . ' <br />
' . $row[6] . ' <br />
' . $row[7] . ', ' . $row[8] . ', ' . $row[9] . ' <br />
</p>
</td>
<td width="35%">
<p><strong>Order Total:</strong><br />
' . $row[14] . ' pts <br />
</p>
<p><strong>Date:</strong><br />
' . $row[11] . ' <br />
</p>
</td>
</tr>
</table>
<form method="post" action="view-ind-order-test.php">
Has this order been shipped?<br />
Yes:<input type="radio" value="YES" name="shipped"> No:<input type="radio" value="NO" name="shipped"><br />
<input type="submit" name="submit" value="Submit" />
<input type="hidden" name="submitted" value="TRUE" />
<input type="hidden" name="id" value="' . $id . '" />
</form><br />
<p></p>
<table border="0" width="400" cellspacing="1" cellpadding="5">
<tr class="top">
<td align="left" ><b>Product</b></td>
<td align="center"><b>Qty</b></td>
<td align="center"><b>Price</b></td>
</tr>';
$bg = '#dddddd'; // Set the background color.
do { // DO WHILE loop start
$bg = ($bg=='#eaeced' ? '#dddddd' : '#eaeced');
echo '<tr bgcolor="' . $bg . '">';
echo '<td align="left">' . $row[22] . '</td>
<td align="center">' . $row[19] . '</td>
<td align="center">' . $row[20] . '</td>
</tr>';
} while($row = mysql_fetch_array($result, MYSQL_NUM));// end of WHILE loop
echo '</table>
<br><br>
<p> << Back to Orders</p>
<p> </p>
<p> </p>
<p> </p>
';
} else { // Not a valid user ID.
echo '<h1 id="mainhead">Page Error</h1>
<p class="error">This page has been accessed in error.</p><p><br /><br /></p>';
}
mysql_close(); // Close the database connection.
?>
<p>footer</p>
<?php
include ('./includes/footer_admin_user.html'); // Include the HTML footer.
?>
#gview is right that you should alter your table and make it DEFAULT CURRENT_TIMESTAMP. If you cannot alter the table, you can change your update query to set order_date = order_date, which will prevent it from being updated:
UPDATE orders SET shipped='$shipped', order_date = order_date WHERE order_id='$id'
This is a well known issue with mysql timestamps. You can read about the ins and outs of timestamps Here
The default behavior of the timestamp is to update on insert AND update. You can change this by altering the table and adding a default to the timestamp definition:
DEFAULT CURRENT_TIMESTAMP
I'd make another field in the DB called "order_time" or something like that. It can be good to know both the original date and the updated date. timestamp will update every time some content is changed unless you modify the settings.
Use PHP's date() function as a variable for the order_time column and give it the exact time layout you want.

Categories