How to get the name/id of multiple buttons - php

I have gotten the id numbers of users from my database, and I want to make a button for each user. My code makes a table that shows all the IDs and creates a button for each one. I'm having trouble figuring out how to get the name of those buttons for use in other code. The error I am getting is "undefined variable" (in the 3rd line), which I am most likely getting because I am going at getting the button names wrong.
Basically, the $_POST in the third line is wrong (among perhaps other things). My question is how would one get the name (or id?) of the buttons I have made: how should I fix the $_POST or should I use something else entirely?
<?php
if ($_SERVER["REQUEST_METHOD"] == "POST"){
if(isset($_POST[$n])) header("location:" . $n . ".php");
}
?>
<div id="mod_user">
<table id='mod_table'>
<th class='ttop'>#</th>
<th class='ttop'>Page</th>
<?php
$result = $db->prepare("SELECT * FROM User");
$result->execute();
while ($row = $result->fetch(PDO::FETCH_ASSOC)){
$n=$row["UserID"];
?>
<form action="" method="post">
<tr>
<td class='tben'><?php echo $n; ?></td>
<td class='tben'><button type='submit' name=<?php echo $n; ?> >Go here</button></td>
<br />
</tr>
</form>
<?php
} ?>
</table>
</div>

You can try like this:
<td class='tben'><button type='submit' name="usernames[<?php echo $n ?>]" >Go here</button></td>
So you can get button name from $_POST["usernames"] array as below
foreach($_POST["usernames"] as $username => $btn_value)
echo "$username => $btn_name";

Related

Using HTML buttons in PHP loops

I have a html table displayed using foreach loop in php. And I do even have buttons to be clicked in multiple rows. And the code goes like this:
<form method="post">
<table>
<tr> <th> Item </th> <th>Click to select</th></tr>
<?php
$query="select items from items_table";
$result=$con->query($query); //$con is connection variable already initialized
$row=mysqli_fetch_assoc($result);
foreach ($row as $index) //loop
{
?>
<tr>
<td><?php echo $index['items']; ?> </td>
<td><input type="button" value="select"> </td> //button here
</tr>
<?php } ?>
</table>
</form>
Now how can I get to know which button was pressed?
I have read some web pages, which says we need to be using AJAX, and I'm a newbie with no knowledge of how it works.. Please help me out!
I tried to have button inside a loop and expected that the buttons works correctly directly. But it gives wrong output.
If I got what u want I'd say you should handle your button or input
Some ways available
$index['items']
Is Not Correct where u used
<input value=<?php echo $row['id'] ?>
<input name=foo[<?php echo $row['id'] ?>] value=<?php echo $row['id'] ?> >
<input name='foo[]' value=<?php echo $row['id'] ?> >
Then handle them :
<?php
foreach($_REQUEST['foo'] as $name =>
$value){
echo $name ."posted and its value
is:". $value;
}
?>
OR
<?php
echo 'value of foo[1] Is '.$_REQUEST['foo[1]'] ;
?>
You can use FOR EXAMPLE $row['name'] Or any field name u have in your table intead of $row['id'] that I gave

can't delete from specific row from generate table from mySQL

Hye, i'm working on a small project of Inventory system. Everything is okay until this last part. I have included a delete button at the end of each row for user to delete any item of choice, but when user press the delete button, it deleted the last row of the table, instead of the row/item of choices, where is my mistake in my coding?
Thank you!
<?php
$result= mysql_query("SELECT * from Staff ORDER BY status");
$count=1;
while($row=mysql_fetch_array($result)){
?>
<tr>
<td align="left"><?php echo $count; ?></td>
<td align="left"><?php echo $row['staffId']; ?></td>
<td align="left"><?php echo $row['name']; ?></td>
<td align="left"><?php echo $row['address'];?></td>
<td align="left"><?php echo $row['pNum'];?></td>
<td align="left"><?php echo $row['status'];?></td>
<td align="left"><?php echo $row['type'];?></td>
<td><input type="submit" name="deleteStaff" value="Delete" onClick="displayMessage()">
<input type="hidden" name="staffId1" value="<?PHP echo $row['staffId']; ?>">
</td>
</tr>
</tbody>
<?php
$count++; }
if(isset($_POST['deleteStaff'])){
$id=$_POST['staffId1'];
$result=mysql_query("DELETE from Staff WHERE staffId='$id' ");
if($result){
echo '<script> location.replace("viewStaff.php"); </script>';
}
else{
?>
<script>
alert ("Fail to delete data")
window.location.href='viewStaff.php'
</script>
<?PHP
}
}
?>
I've encountered this error before as well. I think the error is happening since you're calling the same "onclick" function for each array result.
Instead, create a link to a page where you can run the php deletion script and pass the staffID into the URI and Get that in the php deletion script that you created.
example
<form action="deletion_script.php?staffid=<?php echo $staffid; ?>">
Put that inside of the td tag
Then in your deletion_script.php file, put something like this
<?php
//get staffid from URI
$staffid = $_GET['staffid'];
$sql="DELETE FROM $table_name WHERE staffid = '$staffid'"
$result = mysqli_query($connect, $sql);
if($result) {
//send back to the page you want
header("Location: ../inventory.php");
}
?>
This worked for me, and how I handle all situations like this from now on. You'll need to adjust the code a little to fit your set up.
since the name for the hidden field is the same for all rows being generated the post request is pulling the value of the last row( also "staffId1" ).
I recommend either using a individual form for each row in which case your code doesn't change as much or use js to get the required staffID using selectors
If you include the same hidden field (StaffId1) for every record it will contain more then one value.
You are now listening to the pressed SUBMIT so you don't need the hidden field. You can just get the value if the pressed SUBMIT.
Button
type="submit" name="staffId" value="<?php echo $id ?>"
Php
$id=$_POST['staffId'];

Store PHP/SQL foreach form items in variables

Sorry I'm a bit of a noob when it comes to PHP but I just wondered if someone had an idea on how I could solve this PHP/SQL problem.
I have a PDO statement that gets all users from a database.
With the array of users from the database I create a foreach loop to display all of the users in a table which I want to use to select a specific user, enter a number in the row of the user I select, then click submit and store the users name and also the number. I will use this information to populate another database later.
My question is, I cant seem to reference the user or the number in the table to extract the user and number I enter. When I try and request the numbered entered in the index.php, it will only ever display a number if I enter a number for a the final user in the table. When I try and view the FullName it never works and I get 'Undefined index: FullName' error.
I also specified to 'POST in the form but it doesnt seem to be doing that.
Does anyone have any ideas?
Thanks
//function.php
function getName($tableName, $conn)
{
try {
$result = $conn->query("SELECT * FROM $tableName");
return ( $result->rowCount() > 0)
? $result
: false;
} catch(Exception $e) {
return false;
}
}
//form.php
<form action "index.php" method "POST" name='form1'>
<table border="1" style="width:600px">
<tr>
<th>Name</th>
<th>Number Entered</th>
<tr/>
<tr>
<?php foreach($users as $user) : ?>
<td width="30%" name="FullName">
<?php echo $user['FullName']; ?>
</td>
<td width="30%">
<input type="int" name="NumberedEntered">
</td>
</tr>
<?php endforeach; ?>
</table>
<input type="submit" value="submit"></td>
</form>
//index.php
$users = getName('users', $conn);
if ( $_REQUEST['NumberedEntered']) {
echo $_REQUEST['NumberedEntered'];
echo $_REQUEST['FullName'];
}
The variable FullName isn't transmitted by your form to index.php. Only values of form elemnts are sent. You can add a hidden form field, that contains FullName like this:
<input type="hidden" name="FullName" value="<?php echo $user['FullName']">
But your second problem is, that your foreach loop will create several input fields with the exact same name. You won't be able to recieve any of the entered numbers, except the last one. have a look at this question for possible solutions.
Update
Putting each row in individual form tags should solve your problem:
<?php foreach($users as $user) : ?>
<form action="index.php" method="POST">
<tr>
<td align="center" width="40%" >
<?php echo $user['FullName']; ?>
<input type="hidden" name="FullName" value="<?php echo $user['FullName']; ?>" />
</td>
<td width="30%">
<input name="NumberedEntered"/>
</td>
<td>
<input type="submit" value="submit"/>
</td>
</tr>
</form>
<?php endforeach; ?>

How to get value from html select option using GET

I am creating a student login site for tutoring center. After a student logged in tutor can see student information and tutor also can submit student information along with tutor name. My problem is whatever i select the tutor name it always insert the last tutor name. I am using PDO for database connection. please can anybody give me an idea how can i solve this problem.Thanks..
Here is my html form code:
<form action="" method="post">
<table border="1">
<tr>
<th>Student Name</th>
<th>course</th>
<th>Tutor</th>
<th>Actions</th>
</tr>
<?php
//select all users from database
$rows = $database->selectFromOnline();
foreach($rows as $row){
$time = $row['time_out'];
?>
<tr>
<td> <?php echo $row['user_name'] ?></td>
<td> <?php echo $row['course'] ?> </td>
<td>
<select name='tutor'>
<?php
//select all instructor from instructor table
$sqls = $database->selectFromTutor();
foreach($sqls as $sql){
echo"<option value='$sql[tutor_ln]'> $sql[tutor_ln] </option>";
}
?>
</select>
</td>
<?php
echo" <td> <a href='tutor.php?user_name=$row[user_name]&&course=$row[course]&&tutor=$sql[tutor_ln]'>Delete</a></td>";
?>
</tr>
<?php
}
?>
</table>
</form>
This is my inserting code:
if(isset($_GET['user_name'])){
$user_name = $_GET['user_name'];
$course = $_GET['course'];
// if i use $_POST['tutor'] it gives me undefined variable error
$tutor = $_GET['tutor'];
//insert into report database table
$database->insetIntoReport($user_name, $course, $tutor);
//Redirect to current page
header('Location: tutor.php');
exit;
}
?>
You're outputting multiple <select name='tutor'> in your form. One select for EVERY time that inner ->selectFromTutor() is executed. As such, you'll get MULTIPLE instances of the tutor select, and only the LAST one will be submitted with the rest of the form.
Your form says <form action="" method="post"> you should be using $_POST variables in your code.
If you are using method="post" on your form, you should use $_POST[]
In addition to the other answers, you could also use $_REQUEST if do not want to bother, whether a form was sent via POST or GET.
I guess you are not willing to use post then you should write a javascript function like
<script type="text/javascript">
function DeleteTutor(name,course){
var tutor=document.getElementById('tutor').value;
window.location.href = 'tutor.php?username='+name+'&course='+course+'&tutor='+tutor;
}
</script>
capture name and course in variables $name and $course and your delete link modified to
<?php echo"<td> <a onclick=\"DeleteTutor('$name', '$course')\">Delete</a></td>"; ?>
Don't forget to add id to select for this to work
<select name='tutor' id="tutor">

PHP Update query not receiving variable already defined in page

Hi I'm trying to update a single field from a HTML form, for some reason one of the session variables I am passing to the update query is not being accepted. I have already echoed the variable in the page so am fairly certain it exists in memory.
NB, I know my code is horrifically insecure but I'm learning PHP and once I've got the basics working Ill go over it and bring it upto best practice standards.
E2A: If I do var_dump($filename); before trying to run the query it returns string(6) "356/18", after the query it returns NULL. I'm not unsetting the variable anywhere so where could it be going!
Here is my form:
<form method="post" action="">
<p>Your username is: <?php echo $_SESSION['userid'] ?> Your company ID is: <?php echo $companyid['id']?></p>
<h3>Please enter note for file: <?php echo $filename; ?></h3>
<table width="200" cellpadding="5">
<tr>
<th width="18%" align="right" nowrap>Add Note: </th>
<td width="82%" nowrap>
<input type="text" name="note" />
</td>
</tr>
<tr>
<td colspan="2" width="100%" nowrap>
<input type="submit" value="Submit" name="Submit" />
</td>
</tr>
</table>
</form>
Here is my UPDATE query:
$sql = "UPDATE fields SET Notes = ('".mysql_real_escape_string(stripslashes($_REQUEST['note']))."')
WHERE companyId='".$companyid['id']."' AND fileNumber ='".$filename."'";
if($result = mysql_query($sql)) {
echo "<h1>Thank you</h1>Your information has been entered into our database<br><br>";
echo $sql;
echo $filename;
} else {
echo "ERROR: ".mysql_error();
}
} else {
echoing $sql produces the following:
UPDATE fields SET Notes = ('asdasda') WHERE companyId='11' AND fileNumber =''
and here is the bit where I instantiate the POST vars.
include "header.php";
$checkFiles = "checkFiles.php";
// Catches form input from previous page and stores it into session variable called filename for future reference;
$_SESSION['filename']=$_POST['filename'];
$filename = $_SESSION['filename'];
//User id stuff from previous page too;
$userid = $_SESSION['userid'];
$id = mysql_query("SELECT id FROM users WHERE DXNumber='".$userid."'");
// Returns pointer so fetch it as an array and insert it into variable $companyid for later use;
$companyid = mysql_fetch_array($id);
You need to include session_start() on the top of each file.
Just do:
AND fileNumber ='".$_SESSION[filename]."'";
In your update query.
If that doesn't work, make sure that a value for $_SESSION[filename] is being set.
<h3>Please enter note for file: <?php echo $filename; ?></h3>
Create a input box
<input type="text" name="filename" value="<?php echo $filename; ?>"/>
Then filename value will be pass to $_POST array

Categories