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.
Related
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>' ;
I can't get the page to display the game information I think something is wrong with my select statement.
The game table has following fields:
game_id, game_name, platform, genre, game_description, game_price,
game_image, game_headlines, and game_added_date.
I only what the page to display:
game_name, platform, genre, game_description, game_price, game_image, and game_headlines.
The page runs but won't display the game even if it in the database.
Website URL: http://cs.neiu.edu/~fsef15g9/CS319_Project_Group_9/view_games.php
<?php # add_games.php
include ('includes/session.php');
$page_title = 'Add Games';
include ('includes/header.php');
require_once ('mysqli_connect.php'); // Connect to the db.
// Check if the form has been submitted:
if (isset($_POST['submitted'])){
$errors = array(); // Initialize an error array.
// Check for a game name:
if (empty($_POST['game_name'])) {
$errors[] = 'You forgot to enter game name.';
} else {
$search = mysqli_real_escape_string($dbc, trim($_POST['game_name']));
}
//$where = '%' + '$search' + '%';
$q = "SELECT
game_name AS game,
platform AS pf,
genre AS ge,
game_description AS gd,
game_price AS gp,
game_image AS gi,
game_headlines AS gh
FROM game WHERE game_name LIKE '$search'%";
$r = #\mysqli_query($dbc, $q); // Run the query.
// Count the number of returned rows:
$num = mysqli_num_rows($r);
if ($num > 0) { // If it ran OK, display the records.
// Print how many users there are:
echo "<p>There are currently $num number of games for '$search'.</p>\n";
// Table header.
echo '<table align="center" cellspacing="3" cellpadding="3" width="75%">
<tr><td align="left"><b>Game Name</b></td><td align="left"><b>Platform</b></td><td align="left"><b>Genre</b></td><td align="left"><b>Game Description</b></td><td align="left"><b>Game Price</b></td><td align="left"><b>Game Headlines</b></td></tr>';
// Fetch and print all the records:
while ($row = mysqli_fetch_array($r, MYSQLI_ASSOC)) {
echo '<tr><td align="left">' . $row['game'] . '</td><td align="left">' . $row['pf'] . '</td><td align="left">' . $row['ge'] . '</td><td align="left">' . $row['gd'] . '</td><td align="left">' . $row['gp'] . '</td><td align="left">' . $row['gi'] . '</td><td align="left">' . $row['gh'] . '</td></tr>';
}
echo '</table>'; // Close the table.
mysqli_free_result ($r); // Free up the resources.
} else { // If no records were returned.
echo '<p class="error">There are currently no registered users.</p>';
}
mysqli_close($dbc); // Close the database connection.
}
?>
<div class="page-header">
<h1 style="font-size:40px"><center>Search Games</center></h1>
</div>
<form class="form-signin" role="form" action="view_games.php" method="post">
<center><p><input type="normal" placeholder="Enter Game Name" required autofocus name="game_name" maxlength="60" value="<?php if (isset($_POST['game_name'])) echo $_POST['game_name']; ?>" />
<button style="display:inline; padding:10px; margin-bottom:5px" type="submit" name="submit" class="btn btn-sm btn-primary" />Add Game</button>
<input type="hidden" name="submitted" value="TRUE" /></p></center>
</form>
<?php
include ('includes/footer.html');
?>
Your query is incorrect, as you have your wildcard % outside the quotes
WHERE game_name LIKE '$search'%
Need to move the % inside the quotes
WHERE game_name LIKE '$search%'
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:(£)</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.
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
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.
}