PHP trouble using $_POST in a loop - php

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

Related

How to associate query with changing variable in PHP

I'm in need of a bit help. I'm trying to find out how to associate a specific query (deletion of a record) with not the id of a record, but the record with which another query (selection of a record) is echoed out.
This line of code totally works when the id is specified, but again I need it for the record that gets called, where the id can skip numbers if I delete a record.
$querytwo = "DELETE FROM `paginas` WHERE id = 5";
I've got a table in my phpmyadmin database with columns 'id', 'pagetitle', 'toevoeging' (addition in Dutch) , 'message'. First one is an INT, rest are varchars/text.
This may be a stupid question, I'm sorry for that. I'm still new to PHP, and to programming in general.
Here is the code. I've commented on lines code to clarify. Thanks you!.
<?php
if (isset($_SESSION['email'])) //if the admin is active, forms can be written out.
{
echo '</nav>
<br><br> <div class="inlogscript">
<form action="verstuurd.php" method="post">
<input type="text" placeholder="Titel" method="POST" name="pagetitle" /><br><br>
<input type="text" placeholder="Toevoeging" method="POST" name="toevoeging" /><br><br>
<textarea class="pure-input-1-2" placeholder="Wat is er nieuws?" name="message"></textarea><br>
<input type="submit" value="Bevestigen" />
</form></div>';
}
?>
<div class="mainContent">
<?php
include_once("config.php"); //this is the database connection
$query = "SELECT * FROM paginas "; //selects from the table called paginas
$result = mysqli_query($mysqli, $query);
while($row = mysqli_fetch_assoc($result))
{
$pagetitle = $row['pagetitle'];
$toevoeging = $row['toevoeging'];
$message = $row['message'];
echo '<article class="topcontent">' . '<div class="mct">' . '<h2>' . "$pagetitle" .'</h2>' . '</div>' . "<br>" .
'<p class="post-info">'. "$toevoeging" . '</p>' . '<p class="post-text">' . '<br>'. "$message" . '</p>' .'</article>' . '<div class="deleteknop">' . '<form method="post">
<input name="delete" type="submit" value="Delete Now!">
</form>' . '</div>' ;
} //This long echo will call variables $pagetitle, $toevoeging and &message along with divs so they automatically CSS styled,
//along with a Delete button per echo that has the 3 variables
$querytwo = "DELETE FROM `paginas` WHERE id = 5";
if (isset($_POST['delete'])) //Deletes the query if 'delete' button is clicked
{
$resulttwo = $mysqli->query($querytwo);
}
?>
</div>
</div>
Also here is the Insert INTO query of the records. Thanks again!
$sql = "INSERT INTO paginas (pagetitle,toevoeging, message)
VALUES ('$_POST[pagetitle]','$_POST[toevoeging]','$_POST[message]')";
//the insertion into the table of the database
if ($MySQLi_CON->query($sql) === TRUE) {
echo "";
} else {
echo "Error: ". $sql . "" . $MySQLi_CON->error;
}
This won't be sufficient but, to begin with your echo :
echo '<article class="topcontent">
<div class="mct">
<h2>' . $pagetitle .'</h2>
</div><br>
<p class="post-info">'. $toevoeging . '</p>
<p class="post-text"><br>'.$message.'</p>
</article>
<div class="deleteknop">
<form method="post">';
// you ll want to use $_POST["id"] array to delete :
echo '<input type="hidden" name="id" value="'.$row['id'].'">
<input name="delete" type="submit" value="Delete Now!">
</form>
</div>' ;

How to rember $_POST var from previous <form method>?

if ($_SERVER['REQUEST_METHOD'] != 'POST'){
echo '<form method="post" action="">
<select name="class_name">
<option value="class_id">name</option>
</select>
<input type="submit" value="Proceed">
</form>';
}
else{
$_SESSION['var_name'] = $_POST['class_name'];
$sql = "SELECT (...) students.class_id = " . $_SESSION['var_name'];
$que = mysqli_query($conn, $sql);
echo '<table border 1>
<tr><th>Last</th><th>Name</th><th>Add</th></tr>';
while ($row = mysqli_fetch_array($que)){ //<-HERE I GOT A ERROR
echo '<tr><td>' . $row['user_last'] . '</td><td>' . $row['user_name'] . '</td>
<td> <form method="post" action="">
<input type="hidden" name="usr_id" value = "' . $row['user_id'] . '"/>
<input type="submit" name="button" value="+" />
</form>
</td>
</tr>';
}
echo '</table>';
if (isset($_POST['button'])){
//DOESEN'T MATTER
}
}
Ok, so my problem is that after clicking on my button from the second i got the error mysqli_fetch_array() expects parameter 1 to be mysqli_result, boolean given on line I've commented above. I know that after clicking the value of _SESSION var is lost. My question is how to store this thing. I've tried session management but nothing.
I forgot to add, that I'm opening a session in included file.
Use Sessions, and make sure you have a
session_start();
on each page.

Error in updating a mysql table

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

php mysql based on user input form

I am having trouble using a checkbox to select one or multiple fields of data for PHP/AJAX to process and display. I have the PHP/AJAX working great on my <select>s but as soon as I try setting up the checkbox all hell breaks lose.
I also am very unsure on how to further prevent SQL injection on the site so if anyone could fill me in a little more about this I would GREATLY appreciate it! I read the link I was provided and just don't understand how bid_param or PDO works exactly.
The ajax script:
(I can't seem to insert the ajax/js so I'll leave a link to the live site)
Link to Agent search page
My php page that displays the data:
<div id="bodyA">
<h1>Find a Local OAHU Agent.</h1>
<!-- This is where the data is placed. -->
</div>
<div id="sideB">
<div class="sideHeader">
<em>Advanced Search</em>
</div>
<form class="formC">
<label for="last">Last Name</label><br />
<select id="last" name="Last_Name" onChange="showUser(this.value)">
<?php
include 'datalogin.php';
$result = mysqli_query($con, "SELECT DISTINCT Last_Name FROM `roster` ORDER BY Last_Name ASC;");
echo '<option value="">' . 'Select an Agent' .'</option>';
while ($row = mysqli_fetch_array($result)) {
echo '<option value="'.$row['Last_Name'].'">'.$row['Last_Name'].'</option>';
}
?>
</select>
<label for="company">Company</label><br />
<select id="company" name="users" onChange="showUser(this.value)">
<?php
include 'datalogin.php';
$result = mysqli_query($con, "SELECT DISTINCT Company FROM `roster` ORDER BY Company ASC;");
echo '<option value="">' . 'Select a Company' .'</option>';
while ($row = mysqli_fetch_array($result)) {
if ($row['Company'] == NULL) {
} else {
echo '<option value="'.$row['Company'].'">'.$row['Company'].'</option>';
}
}
?>
</select>
<label for="WorkCity">City</label><br />
<select id="WorkCity" name="WorkCity" onChange="showUser(this.value)" value="city">
<?php
include 'datalogin.php';
$result = mysqli_query($con, "SELECT DISTINCT WorkCity FROM `roster` ORDER BY WorkCity ASC;");
echo '<option value="">' . 'Select a City' .'</option>';
while ($row = mysqli_fetch_array($result)) {
echo '<option value="'.$row['WorkCity'].'">'.$row['WorkCity'].'</option>';
}
?>
</select>
<label for="WorkZipCode">Zip Code</label><br />
<select id="WorkZipCode" name="WorkZipCode" onChange="showUser(this.value)">
<?php
include 'datalogin.php';
$result = mysqli_query($con, "SELECT DISTINCT WorkZipCode FROM `roster` ORDER BY WorkZipCode + 0 ASC;");
echo '<option value="">' . 'Select a Zip Code' .'</option>';
while ($row = mysqli_fetch_array($result)) {
echo '<option value="'.$row['WorkZipCode'].'">'.$row['WorkZipCode'].'</option>';
}
?>
</select>
<label for="agent">Agent Expertise</label><br />
<label for="ancillary"><input type="checkbox" value="Ancillary" name="Ancillary[]" id="ancillary" />Ancillary</label><br />
<label for="smallgroup"><input type="checkbox" value="Smallgroup" name="Smallgroup[]" id="smallgroup" />Small Group</label><br />
<label for="largegroup"><input type="checkbox" value="LargeGroup" name="LargeGroup[]" id="largegroup" />Large Group</label><br />
<label for="medicare"><input type="checkbox" value="Medicare" name="Medicare[]" id="medicare" />Medicare</label><br />
<label for="longterm"><input type="checkbox" value="LongTerm" name="LongTerm[]" id="longterm" />Long Term Care</label><br />
<label for="individual"><input type="checkbox" value="Individual" name="Individual[]" id="individual" />Individual Plan</label><br />
<label for="tpa"><input type="checkbox" value="TPASelfInsured" name="TPASelfInsured[]" id="tpa" />TPA Self Insured</label><br />
<label for="ppaca"><input type="checkbox" value="CertifiedForPPACA" name="CertifiedForPPACA[]" id="ppaca" />Certified for PPACA</label><br />
</form>
</div>
My php page that pulls the info and places it into a container on the page:
$q = (isset($_GET['q'])) ? $_GET['q'] : false; // Returns results from user input
include 'datalogin.php'; // PHP File to login credentials
$sql="SELECT * FROM `roster` WHERE Company = '".$q."' OR Last_Name = '".$q."' OR WorkCity = '".$q."' OR WorkZipCode = '".$q."' ORDER BY Last_Name ASC";
$result = mysqli_query($con,$sql) // Connects to database or die("Error: ".mysqli_error($con));
echo "<h1>" . "Find a Local OAHU Agent." . "</h1>";
while ($row = mysqli_fetch_array($result)) { // Gets results from the database
echo "<div class='agentcon'>" . "<span class='agentn'>" . "<strong>".$row['First_Name'] . " " .$row['Last_Name'] . "</strong>" . "</span>" . "" . "<span class='email'>".$row['Email'] . "</span>" . "" ."<div class='floathr'></div>";
if ($row['Company'] == NULL) {
echo "<p>";
}
else {
echo "<p>" . "<strong>" .$row['Company'] . "</strong>" . "<br>";
}
echo $row['WorkAddress1'] . " " .$row['WorkCity'] . "," . " " .$row['WorkStateProvince'] . " " .$row['WorkZipCode'] . "<br>";
if ($row['Work_Phone'] !== NULL) {
echo "<strong>" . "Work" . " " . "</strong>" .$row['Work_Phone'] . "<br>";
}
if ($row['Fax'] !== NULL) {
echo "<strong>" . "Fax" . " " . "</strong>" .$row['Fax'] . "<br>";
}
echo "<strong>" . "Agent Expertise:" . "</strong>";
if ($row['Ancillary'] == 1) {
echo " " . "Ancillary" . "/";
}
if ($row['SmallGroup'] == 1) {
echo " " . "Small Group" . "/";
}
if ($row['IndividualPlans'] == 1) {
echo " " . "Individual Plans" . "/";
}
if ($row['LongTermCare'] == 1) {
echo " " . "Long Term Care" . "/";
}
if ($row['Medicare'] == 1) {
echo " " . "Medicare" . "/";
}
if ($row['LargeGroup'] == 1) {
echo " " . "LargeGroup" . "/";
}
if ($row['TPASelfInsured'] == 1) {
echo " " . "TPA Self Insured" . "/";
}
if ($row['CertifiedForPPACA'] == 1) {
echo " " . "Certified For PPACA";
}
echo "</p>" . "</div>";
}
mysqli_close($con);
?>
I appreciate any and all help on this topic! Any time I add the checkbox values to my php file it ends up displaying everyone in the database for all fields in the form.
I am also trying to prevent sql injection on this but how can a user do this if I don't have a field the user can input text into?
EDIT As of today I gave a try with using jQuery to activate the checkboxes and then call some AJAX.
Here is the script I wrote and it is pulling an agent, just not everyone that has that "expertise".
$('input').click(function() {
$.ajax({
url: "process.php",
data: { value: 1},
success: function (data) {
$('#bodyA').html(data);
}
});
});
Here's a quick example of something I recently worked on in which I needed to loop through multiple checkboxes and pass those values into a SQL statement. Although this example happens on a button click, hopefully its something along the lines of what you are trying to accomplish, or at least at start... :)
<?php
$array = array();
if (isset($_POST['medicare'])) {
foreach ($_POST['medicare'] as $value) {
array_push($array, $value);
}
}
// this will return the value of each selected checkbox, separating each with a comma
$result = implode(",", $array);
// if you want to loop through each individually (for example pass each into a SQL statement)
foreach ($_POST['medicare'] as $value) {
// Do your SQL here
// $value will be the value of each selected checkbox (Smallgroup, Largegroup, etc.)
$sql = "insert into tablename(fieldname) values ('$value')"; // just an example
}
?>
<input type="checkbox" name="medicare[]" id="smallgroup" value="Smallgroup" />
<label for="smallgroup">Small Group</label>
<br />
<input type="checkbox" name="medicare[]" id="largegroup" value="Largegroup" />
<label for="largegroup">Large Group</label>
<br />
<input type="checkbox" name="medicare[]" id="medicare" value="Medicare" />
<label for="medicare">Medicare</label>
<br />
<input type="checkbox" name="medicare[]" id="individualplan" value="IndividualPlan" />
<label for="individualplan">Individual Plan</label>
<br />
<input type="submit" value="Submit" id="btnSubmit" name="btnSubmit" />
UPDATE
Instead of setting one variable, try setting a variable for each select control and putting your SQL statement in a foreach loop. I just tested this with some dummy data and didn't have any issues with it.
<?php
$lastname = (isset($_GET['Last_Name'])) ? $_GET['Last_Name'] : false;
$users = (isset($_GET['users'])) ? $_GET['users'] : false;
$workCity = (isset($_GET['WorkCity'])) ? $_GET['WorkCity'] : false;
$WorkZipCode = (isset($_GET['WorkZipCode'])) ? $_GET['WorkZipCode'] : false;
foreach ($_GET['medicare'] as $value) {
//echo $value;
$sql="SELECT * FROM roster WHERE Company = '$users' OR Last_Name = '$lastname' OR WorkCity = '$workCity' OR WorkZipCode = '$WorkZipCode' OR Ancillary = '$value' ORDER BY Last_Name ASC";
}
...continue as you were...
?>
I DID IT!! Wohoo! I ended up just making a separate php page called expertise.php to process the checkboxs using jquery/ajax.
The jQuery that achieved this: (Thank god I went onto the jQuery website to look up functions!)
$('input').click(function() {
$.ajax({
url: "expertise.php",
data: { value: 1},
success: function (data) {
$('#bodyA').html(data);
}
});
});
The PHP page is the same as my process.php page except for the sql:
$sql="SELECT * FROM `roster` WHERE Ancillary = '1' AND SmallGroup = '1' AND CertifiedForPPACA = '1' ORDER BY Last_Name ASC";
If anyone would enlighten me more on making this better protected against sql injections, feel free to!
Agent Search Page
Well I at least got both parts of the search working but a new problem has arose :p
Now in the sql I can use AND or OR, with AND it pulls only agents that have everyone of those expertise and with OR it seems to pull everyone. Any ideas?

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