Ok, so I have an input function that allows me to add items to a database, and displays this as a table. As part of the table, I am trying to add delete and edit buttons.
I am trying to figure out the best way to add delete and edit functionality. I'm thinking for editing, I will have to use Javascript. However, for deletions, I am not sure if I should use PHP, Javascript, or some combination therein.
So far, here's my code:
<html>
<header><title>Generic Web App</title></header>
<body>
<form action="addculture.php" method="POST">
<span><input type="text" size="3" name="id" />
<input type="text" name="culture" />
<input type="submit" value="add" /></span>
</form>
<?php
/* VARIABLE NAMES
*
* $con = MySQL Connection
* $rescult = MySQL Culture Query
* $cultrow = MySQL Culture Query Rows
*/
$con = mysql_connect("localhost", "root", "");
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
mysql_select_db("generic");
$rescult = mysql_query("SELECT * FROM culture order by cult_id");
if (!$rescult) {
die('Invalid query: ' . mysql());
}
echo "<table><tbody><tr><th>ID</th><th>Culture Name</th>";
while ($cultrow = mysql_fetch_array($rescult)) {
echo "<tr>" . "<td>" . $cultrow[0] . "</td>" . "<td>" . $cultrow[1] . "</td>" . '<td><button type="button">Del</button></td>' . '<td><button type="button">Edit</button></td>' . "</tr>";
}
echo "</tbody></table>";
?>
</body>
</html>
Currently I have del and edit set as buttons, just for visible reference. What's the best way to deal with a situation where you have multiple buttons like this?
I apologize if my answer is too broad but so is your question.
Both, Editing and Deleting should use a combination of JavaScript and PHP code; for example when the user clicks on the delete button you can send an Ajax request to the server, have the record deleted from the DB and upon successful return from the server-side call, use JavaScript to visually delete the record from the markup. The same would apply to the Edit functionality.
Here's a nice intro on how to perform ajax requests using JQuery:
http://www.devirtuoso.com/2009/07/beginners-guide-to-using-ajax-with-jquery/
The first think I would do is add a value and name to the buttons:
<button type="button" value="$cultrow[0]" name="Delete">Delete</button>
<button type="button" value="$cultrow[0]" name="Edit">Edit</button>
The value of the button is going to be the id of the row, and the name is going to be the action that button will do. The next thing I would do is bind those buttons to actions with jquery.
$('button').click(function(){
//determine whether is delete or edit
//Once you determine what action use the id to make the request
//if delete prompt to verify if yes, ajax the server with a delete request
//if edit redirect user to a page that will handle editing of the row edit.php?id=5
});
For deleting row
1 - Make new page name it del_culture.php
session_start();
$id = base64_decode($_GET['id']);
$con = mysql_connect("localhost", "root", "");
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
$q = mysql_query("DELETE FROM culture WHERE cult_id = '".$id."' ");
if($q):
echo "Done";
else:
echo "ERROR";
endif;
2 - in your page add the following code
while ($cultrow = mysql_fetch_array($rescult))
{
echo "<tr>" . "<td>" . $cultrow[0] . "</td>" . "<td>" . $cultrow[1] . "</td>" . '
<td>Delete' . '<td><button type="button">Edit</button></td>' . "</tr>";
}
For Editing a row add link for edit like i did to page name it edit_cult.php
and do the same as you input put the values from database and then update it
This is your javascript
function performAction(action) {
// ASSIGN THE ACTION
var action = action;
// UPDATE THE HIDDEN FIELD
document.getElementById("action").value = action;
switch(action) {
case "delete":
//we get an array with every input contained into the form, and the form have an id
var aryCheck=document.getElementById('adminform').getElementsByTagName('input');
//now we parse them
var elm=null;
var total=0;
for(cptCnt=0;cptCnt<aryCheck.length;cptCnt++) {
elm=aryCheck[cptCnt];
if(elm.type=='checkbox') {
//we have a checkbox here
if(elm.checked==true){
total++;
}
}
}
if(total > 0) {
if(confirm("Are you sure you want to delete the selected records?")) {
// SUBMIT THE FORM
document.adminform.submit();
}
}
else {
alert("You didn't select any records");
}
break;
case "edit":
//we get an array with every input contained into the form, and the form have an id
var aryCheck=document.getElementById('adminform').getElementsByTagName('input');
//now we parse them
var elm=null;
var total=0;
for(cptCnt=0;cptCnt<aryCheck.length;cptCnt++) {
elm=aryCheck[cptCnt];
if(elm.type=='checkbox') {
//we have a checkbox here
if(elm.checked==true){
total++;
}
}
}
if(total > 1) {
alert("You can only edit one record at a time");
}
else if(total == 0) {
alert("You didn't select a record");
}
else {
document.adminform.submit();
}
break;
default:
}
}
and in your form you need something like this
<form id="adminform" name="adminform" action="<?php $_SERVER['REQUEST_URI'] ?>" method="post">
<img src="/admin/images/news.png" alt="news" title="news" />
<input type="button" class="back" id="backbutton" title="go back" onclick="performAction('back');" />
<input type="button" class="delete" id="deletebutton" title="delete" onclick="performAction('delete');" />
<input type="button" class="archive" id="archivebutton" title="archive" onclick="performAction('archive');" />
<input type="button" class="edit" id="editbutton" title="edit" onclick="performAction('edit');" />
<input type="button" class="add" id="addbutton" title="add" onclick="performAction('add');" />
<table id="admintable">
<tr><th class='tdleft'>
<?php
if($err !=0) {
echo"<input type='checkbox' name='all' onclick='checkAll(adminform);' />";
}
echo "</th><th class='tdright'>Title</th></tr>";
$z = 0;
// Iterate through the results
while ($row = $result->fetch()) {
if($z % 2==0) {
//this means if there is a remainder
echo "<tr class='yellow'>\n";
$z++;
} else {
//if there isn't a remainder we will do the else
echo "<tr class='white'>\n";
$z++;
}
echo "<td class='tdleft'><input type='checkbox' name='id[]' value='{$row['id']}' /></td><td class='tdright'><a href='/admin/news/edit-news-".$row['id']."'>{$row['title']}</a></td></tr>";
}
?>
</table>
<input type="hidden" id="action" name="action" value="" />
and at the top of your page before the html put
if($_POST && array_key_exists("action", $_POST)){
// CARRY OUT RELAVANT ACTION
switch($_POST['action']) {
case "edit":
foreach($_POST['id'] as $value) {
$id = $value;
}
header('Location: /admin/blogs/edit-blog-'.$id);
break;
case "delete":
if(!empty($_POST['id'])) {
//do your delete here
}
break;
}
}
}
Related
***UPDATE
I've done away with table elements as suggested and am using CSS. I've also seen that there's a "form" attribute, I've tried that, too. When I submit, it is still acting as it did before - sending the wrong value because it was sending the whole table. I've updated the below with the updated HTML output and the PHP code. It looks correct, this is my latest attempt. What am I missing?
I am using PHP to create a form for each row of data. I call to PHP via AJAX. The form builds correctly. Each row correctly lists its values and is in its own form. In this example, there are three rows, thus three forms. When I submit a username on the first row, the ID being sent is from the third row. Not sure what is going on.
AJAX call to PHP FORM - Home Page
<script>
window.onload = function signupForm() {
var xmlHttp = new XMLHttpRequest();
xmlHttp.onreadystatechange = function() {
if(xmlHttp.readyState == 4 && xmlHttp.status == 200) {
document.getElementById("signupForm").innerHTML = this.responseText;
}
}
xmlHttp.open("GET", "ajaxInput.php", true);
xmlHttp.send();
}
</script>
PHP FORM - signupForm.php
<?php
$con=mysqli_connect("localhost","xxxxxx","xxxxxxx","xxxxxxxx");
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$result = mysqli_query($con,"SELECT id, DATE_FORMAT(startTime, '%b-%d-%Y') as eventDate, endTime FROM events
WHERE now() < endTime");
echo "
<style>
.table { display: table; }
.table>* { display: table-row; }
.table>*>* { display: table-cell; padding: 5px; border-style: inset;}
</style>
<div class='table'>
<div>
<div><b>Event Id</b></div>
<div><b>Date</b></div>
<div><b>#username</b></div>
<div><b>Sign Up!</b></div>
</div>";
while($row = mysqli_fetch_array($result))
{
//echo "<form action='ajaxSignup.php' method='post'>";
echo "<div>";
echo "<div>" . $row['id'] . "</div>";
echo "<div>" . $row['eventDate'] . "</div>";
echo "<div><form id='form" .$row['id']. "' method='post'><input class='formSignup' type='text' name='pi_username' id='pi_username' maxlength='20' placeholder='#username' form='form" .$row['id']. "'></div>";
echo "<div><input class='formSignup' type='hidden' name='event_id' id='event_id' value='" . $row['id'] . "' form='form" .$row['id']. "'>
<input name='submit". $row['id'] . "' type='submit' value='Sign up!' onclick='signup(); return false;'></form></div>";
echo "</div>";
}
//echo "</div>";
echo "</div>";
mysqli_close($con);
?>
The table draws correctly. I've put form tag in various places as well. Below, I'm using the form attribute in the input tags. The table is being drawn with CSS instead of the table elements.
<html>
<head></head>
<body>
<p>Something here</p>
<div id="signupForm">
<style>
.table { display: table; }
.table>* { display: table-row; }
.table>*>* { display: table-cell; padding: 5px; border-style: inset;}
</style>
<div class="table">
<div>
<div><b>Event Id</b></div>
<div><b>Date</b></div>
<div><b>#username</b></div>
<div><b>Sign Up!</b></div>
</div>
<div>
<div>11</div>
<div>Feb-25-2021</div>
<div><input class="formSignup" type="text" name="pi_username" id="pi_username" maxlength="20" placeholder="#username" form="form11"></div>
<div>
<input class="formSignup" type="hidden" name="event_id" id="event_id" value="11" form="form11">
<form id="form11" method="post"><input name="submit11" type="submit" value="Sign up!" onclick="signup(); return false;"></form>
</div>
</div>
<div>
<div>12</div>
<div>Feb-26-2021</div>
<div><input class="formSignup" type="text" name="pi_username" id="pi_username" maxlength="20" placeholder="#username" form="form12"></div>
<div>
<input class="formSignup" type="hidden" name="event_id" id="event_id" value="12" form="form12">
<form id="form12" method="post"><input name="submit12" type="submit" value="Sign up!" onclick="signup(); return false;"></form>
</div>
</div>
<div>
<div>13</div>
<div>Feb-27-2021</div>
<div><input class="formSignup" type="text" name="pi_username" id="pi_username" maxlength="20" placeholder="#username" form="form13"></div>
<div>
<input class="formSignup" type="hidden" name="event_id" id="event_id" value="13" form="form13">
<form id="form13" method="post"><input name="submit13" type="submit" value="Sign up!" onclick="signup(); return false;"></form>
</div>
</div>
</div>
</div>
As can be seen in the PHP, each row is its own form. But looking at the Elements in developer tools, the form is closing early. I think this is related to the issue.
Elements
When I enter a username on row one (top row), the username doesn't seem to make it and the ID that does make it is 13 instead of 11.
AJAX Script to process Submit button onclick (Home page)...
<script>
function signup() {
var elements = document.getElementsByClassName("formSignup");
var formData = new FormData();
for(var i=0; i<elements.length; i++) {
formData.append(elements[i].name, elements[i].value);
}
var xmlHttp = new XMLHttpRequest();
xmlHttp.onreadystatechange = function() {
if(xmlHttp.readyState == 4 && xmlHttp.status == 200) {
document.getElementById("signupSuccess").innerHTML = this.responseText;
}
}
xmlHttp.open("post", "ajaxSignup.php");
xmlHttp.send(formData);
}
</script>
PHP code on signup page. I have some echos early on that show the id is 13, not 11 and no username is present.
<?php
$pi_username = $high_score = $attempts = $event_id = "";
echo $event_id;
echo $pi_username;
if ($_SERVER["REQUEST_METHOD"] == "POST") {
$pi_username = test_input($_POST["pi_username"]);
$event_id = test_input($_POST["event_id"]);
}
function test_input($data) {
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
echo $event_id;
echo $pi_username;
if($_SERVER["REQUEST_METHOD"] == "POST") {
/* Attempt MySQL server connection. Assuming you are running MySQL
server with default setting (user 'root' with no password) */
$link = mysqli_connect("localhost", "xxxxxxx", "xxxxxxx", "xxxxxx");
// Check connection
if($link === false){
die("ERROR: Could not connect. " . mysqli_connect_error());
}
//check if user has already signed up for event
$alreadySignedUp = mysqli_query($link, "SELECT count(*) AS total FROM signup WHERE event_id = $event_id AND pi_username = '$pi_username'");
while ($worm = mysqli_fetch_array($alreadySignedUp)){
//echo $bird['total'];
if($worm['total'] >= 1 ){
echo "You have already signed up for this event.";
echo $event_id;
echo $pi_username;
echo $worm['total'];
mysqli_close($link);
return;
}
}
// Attempt insert query execution
$sql = "INSERT INTO signup (event_id, pi_username) VALUES ('$event_id', '$pi_username')";
if(mysqli_query($link, $sql)){
echo "You have been successfully added to event ".$event_id."!";
mysqli_close($link);
return;
} else{
echo "ERROR: Could not able to execute $sql. " . mysqli_error($link);
}
}
else {
echo "Don't forget to submit your high scores before you leave!";
}
?>
Where am I going wrong?
The signup() function was looking for elements with the same class (formSignup). All input fields had the same class name and were all being sent to the signup() function. I've updated the class name to be unique for each row. Now only a single row is being sent. The signup() function was updated to:
window.onload = function signupForm(getClass) {
var xmlHttp = new XMLHttpRequest(getClass);
Example of an input field with a unique class name:
<input class='formSignup" .$row['id']. "' type='hidden' name='event_id' id='event_id' value='" . $row['id'] . "' form='form" .$row['id']. "'>
Removed table elements and created a CSS-styled 'table' as suggested. All working now. Question updated with CSS-Styled table.
I'm in the middle of making a simple inventory system for keeping track of equipment going in and out of our doors. The inventory is stored in MYSQL, with a table looking like this: id name storage used location_storage location
This is all fun and games when I create a simple form with PHP, so it stays dynamic with the content from the server. I can update all values with no problem.
But for the sake of simplicity I'm looking into having a drop down menu, with a button, that creates/shows input fields in a form. The reason being is that I will have many rows in my table in the upcoming time. As the forms earlier have been made from server information, I will also need the scripts to be dynamic. Right now I'm stuck thinking about what I should do.
As of now, my code for the bits look like this:
"Static" PHP form:
<form action="<?php $_PHP_SELF ?>" method="POST">
<?php
//conn stuff
$sql = "SELECT id, name, storage, used, location FROM inventory";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
echo ' ' . $row["id"]. ' ' . $row["name"]. '<input type="text" name="newamount[' . $row["id"]. ']" />';
echo '<br>';
}
} else {
echo "0 results";
}
$conn->close();
?>
<input type="submit" name="checkout" value="Check out"/>
<input type="submit" name="checkin" value="Check in"/>
</form>
Check in PHP (check out is identical except for change of + and minus):
if(isset($_POST['sjekkinn'])){
//conn stuff
mysql_select_db( 'experimental' );
$newamount = $_POST['newamount'];
foreach($newamount as $key => $value){
$sql = "UPDATE inventory ". "SET storage = (storage + $value), used = (used - $value)". "WHERE ID = $key " ;
if (empty($value)) continue;
$retval = mysql_query( $sql, $conn );}
if(! $retval ) {
die('Could not update data: ' . mysql_error());
}
echo "Updated data successfully!<br>";
header("Refresh:1");
mysql_close($conn);
}
Those are all working great, but I would like to use something like the code below for a neater setup... Anyone got any advice?
Drop down list generated from MYSQL:
<form action="#" method="post">
<select name="selectinventory">
<?php
//conn stuff
$sql = "SELECT * FROM inventory";
$result = $conn->query($sql);
while ($row = $result->fetch_array()){
echo '<option value="' . $row["id"]. '">' . $row['name'] . '</option>';
}
?>
</select>
<input type="submit" name="submit" value="Add line">
</form>
Okay, so I found my own solution.
I ended up using my table-populated drop down list as I showed you in the last code box of the question. What came to my mind was that I could simply use the jQuery show/hide function.
What I did was to make a script that told (in "readable") div 'x' to show and move when option 'x' was selected and button clicked. I will show you my complete code in the end.
That way I could have my input fields each created inside a div from my table (the same that populated the drop down list), so I could manage them easier (probably possible to do it easier - but if it ain't broken, don't fix it). These were created outside the form. When I then click the previously mentioned button, the div will move inside the form. The next one I select will end up UNDER the previous one, instead of just showing up in table-order.
Feel free to shout any questions!
Here's the complete code:
<form action="<?php $_PHP_SELF ?>" method="post">
<select name="selectinventory" id="selectinventory">
<option selected="selected">Choose one</option>
<?php
//conn stuff
$sql = "SELECT id, name FROM inventory";
$result = $conn->query($sql);
$sql = "SELECT * FROM inventory";
$result = $conn->query($sql);
while ($row = $result->fetch_array()){
echo '<option value="' . $row["id"]. '">' . $row['name'] . '</option>';
}?>
</select>
<div id="btn">Add line</div>
</form>
<script type="text/javascript">
$(document).ready(function(){
$("#btn").click(function(){
$("#" + $("#selectinventory").val()).show();
$("#" + $("#selectinventory").val()).appendTo($(".selecteditems"));
});
});
</script>
<?php
//conn stuff
$sql = "SELECT id, name FROM inventory";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
echo '<div style="display:none" id="' . $row["id"]. '"> ' . $row["id"]. ' ' . $row["name"]. '<input type="text" name="newamount[' . $row["id"]. ']" /><br></div>
';
}
} else {
echo "0 results";
}
$conn->close();
?>
<form action="<?php $_PHP_SELF ?>" method="POST" name="isthisthearrayname">
<div class="selecteditems">
</div>
<input type="submit" name="checkout" value="Check out"/>
<input type="submit" name="checkin" value="Check in"/>
</form>
I'm trying to implement some Ajax on a favourite/unfavourite button. The idea behind it is that when you click it a star changes to yellow and when you click it again, it changes back to grey and so on. It adds and deletes data from a DB.
before I had it like this
<?php
include("classes/event.class.php");
$m = new Event();
$arrayAllEvents = $m->getNonFavo();
$arrayFavorites = $m->getFavo();
$db = new db();
while ($row = mysqli_fetch_assoc($arrayFavorites))
{
$unfavoriteID = $row['f_id'];
$uid = $_SESSION['u_id'];
}
if(isset($_POST['favorite_row']))
{
$uid = $_SESSION['u_id'];
$Fid = $_POST['id_to_be_favo'];
if(!mysqli_query($db->conn, "INSERT INTO favorites (u_id, n_id, f_boolean) VALUES
('". $db->conn->real_escape_string($uid) ."' ,
'". $db->conn->real_escape_string($Fid) ."' ,
'". $db->conn->real_escape_string("1") ."')"))
{
echo mysqli_error($db->conn);
}
}
if(isset($_POST['Unfavorite_row']))
{
$unFid = $_POST['id_to_be_unfavo'];
if(!mysqli_query($db->conn, "DELETE FROM favorites WHERE f_id ='".$unFid."'"))
{
echo mysqli_error($db);
}
}
?>
And the field was a php echo form
<?php
echo "<form method='post'>
<input type ='hidden' name='id_to_be_favo'
value='".$a['n_id']."' />
<input type='submit' class='favoriteFalse' id='FavoBtn' name='favorite_row' value='favorite' />
</form>
<div class='clearfix'> </div>";
?>
I'm trying to change the form to a button and use jQuery/Ajax to switch it.
I've been trying some different solutions I've found online, but none of them seem to work.
What would be the best way to implement this?
Kind regards
<input type='button' class='favorite' id='<?php echo $a['n_id']; ?>' value='favorite' />
<div class='clearfix'> </div>";
using
$(function() {
$(".favorite").on("click".function() {
$.post("whatever.php", {"favorite_row":this.id}, function(data) {
$("#star").html('<img/>',{"src":data.fave==yes"?"true.png":"false.png"});
});
});
Now return {"fave":"yes"} if favorited
What i have is a array of items from my mySQL database and each item has a checkbox. i am trying to make it so when you click on the checkbox it will submit the information to the database for the item that got checked or unchecked. have i have it is unchecked = 1 and checked = 0. this is for where i want to display the item.
Now my issue is I can't seem to get anything to submit into my database, I don't understand jQuery enough to be able to write a function for it, so i need some help. here is what i got for my code.
if(isset($_POST['submit'])){
foreach($_POST['id'] as $id){
$value = (isset($_POST['location'][$id]) && $_POST['location'][$id]=="0" ? '0' : '1');
$insert = mysql_query("UPDATE items SET location='$value' WHERE id='$id'") or die('Insert Error: '.mysql_error());
}
}
echo '<form id="form1" method="post"><input type="submit" name="submit" value="Submit">';
$result = mysql_query("SELECT * FROM items")
or die("Query Failed: ".mysql_error());
$counter = 0;
echo '<div class="specialcontainer">';
while($row = mysql_fetch_array($result)){
list($id, $item_info, $item_img, $price, $sale, $location) = $row;
if($location == '0'){
$set_checked = ' checked="checked" ';
}else{
$set_checked = '';
}
if($counter % 5==0) {
echo '</div>';
echo '<div class="specialcontainer">';
}
echo '<div class="special"><img src="../images/items/'.$item_img.'" width="130" /><br />';
echo $item_info.'<br />';
echo 'Reg. $'.$price.'<br />';
echo 'Sale $'.$sale.'<br />';
echo 'Slide Show: <input type="checkbox" id="ch" value="0" name="location['.$id.']"'.$set_checked.' /><br />';
echo '<input type="button" value="Edit" name="edit" onclick="window.location.href=\'specials.php?action=edit&id='.$id.'\'">';
echo '<input type="button" value="Delete" name="Delete" onclick="window.location.href=\'specials.php?action=delete&id='.$id.'\'">';
echo '<input type="hidden" name="id[]" value='.$id.' />';
echo '</div>';
$counter++;
}
echo '</div>';
echo '<input type="submit" name="submit" value="Submit"></form>';
so as you can see, i do have the submit button there, but my plan is to remove it for the onChange submit. I've tried the onchange="this.form.submit();" in the checkbox parameter but it don't work properly. so i just want it to submit anytime a checkbox gets clicked on kinda thing.
Would an Ajax solution like this work?
$('ch').click(function() {
//this is what goes into $_POST
var data = 'id='+ $(this).attr('name') +'&checked=' + $(this).is(':checked');
$.ajax({
//This would be the url that would handle updating the MySQL Record
url: my_mysql_handler.php,
cache: false,
type: 'POST',
data: data,
success: function(response) {
alert(response); //or whatever you want to do with the success/fail notification
}
});
});
You should try document.getElementById('form1').submit() in the onchange method of your checkbox
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.
}