How do you create a form in PHP where the results entered in from the user will be generated in a table? When I test the pages, I only get the start of the table, key and results(values) fields but no values!
Here is my code (I'm shortening the number of fields to two since forms can be very long:
Order form:
<?php
foreach ($_POST as $key => $entry)
{
$totalfields++;
echo "<tr>\n";
echo "<td>" . $key . "</td>";
if (is_array ($entry)) {
$count = count($entry);
echo "<td>";
for ($i=0; $i<$count; $i++){
echo $entry[$i] . "<br />";
}
echo "</td>";
} else
{
echo "<td>$entry</td>";
}
echo "<tr>\n";
}
?>
<form method="post" action="address to the results form page">
<label for="fname">First Name:</label>
<input type="text" name="fname" id="fname"/><br/>
<br/>
<label for="lname">Last Name:</label>
<input type="text" name="lname" id="lname"/><br/>
<br/>
<p><input type="submit" value="Submit"/></p>
</form>
Results form page:
<div id="results table">
<table border='1'>
<tr>
<th>
Field
</th>
<th>
Results
</th>
</tr>
</table>
</div>
This actually posts fine for me (I used PHP_SELF for the form action). I would however suggest that you use $_SERVER[REQUEST_METHOD] to check for POST:
if( $_SERVER[REQUEST_METHOD] == 'POST' ) { ...
In addition, be explicit about calling the posted variables ($_POST[fname] & $_POST[lnane])
Your PHP generating the table should be in the resulting page, not in the form page. Or else, you can point the action of the form to the same page, to get the results posted and processed on the same page.
EDIT: What I mean is this: PHP — as you may know — is processed server-side. It means that your browser sends a request to the server, the server processes the PHP file and then it serve the client the processed version.
The problem in your code is that you have the PHP script processing the $_POST on the page in which the user is supposed to fill up the form. When a user fills up the form and hit submit, he will get directed to the action page, where the $_POST will be available and processed. Your misunderstanding is in the fact that you expect the $_POST to be available on the page where it's posted, and then to send it automagically to the result page. This is not what happens because the server doesn't have an opportunity to catch the information you sent on the same page, because it has already been served…
…unless you make the form action direct to the same page. Then the server catches the information and processes it.
You could go solving this problems in two ways really.
Point your action to the result page as you are doing now, but move your processing code to the resulting page.
Point your action to the same page.
You may even want to do something fancy, like check if there is $_POST information and, if there isn't, show a form. If there is, show the result. This is not at all difficult to implement as it follows:
<?php
if( $_POST ): ?>
<div id="results table">
<table border='1'>
<thead>
<tr>
<th>
Field
</th>
<th>
Results
</th>
</tr>
</thead>
<tbody>
<?php
foreach ($_POST as $key => $entry)
{
echo "<tr>\n";
echo "<td>" . $key . "</td>";
if (is_array ($entry)) {
$count = count($entry);
echo "<td>";
for ($i=0; $i<$count; $i++){
echo $entry[$i] . "<br />";
}
echo "</td>";
} else
{
echo "<td>$entry</td>";
}
echo "<tr>\n";
}
?>
</tbody>
</table>
</div>
<?php else: ?>
<form method="post" action="<?php echo $_SERVER['PHP_SELF']; ?>">
<label for="fname">First Name:</label>
<input type="text" name="fname" id="fname"/><br/>
<br/>
<label for="lname">Last Name:</label>
<input type="text" name="lname" id="lname"/><br/>
<br/>
<p><input type="submit" value="Submit"/></p>
</form>
<?php endif; ?>
I made a working example for you. Just go to the link and click the Run [F9] button over the top to see it in action:
Working example
Related
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
This is the code for the admin panel of a certain site. Appointments asked by customers will be shown in this page. The admin will be able to change the appointments based on availability.
<?php
while($row = mysqli_fetch_assoc($result)){
?>
<form action="adminEdit.php" method="POST">
<tr>
<td><input type="text" id="name" value="<?php echo $row['Name'];?>"></input></td>
<td><input type="text" id="address" value="<?php echo $row['Address'];?>"></input></td>
<td><input type="text" id="phone" value="<?php echo $row['Phone'];?>"></input></td>
<td><input type="text" id="license" value="<?php echo $row['Car_License_No'];?>"></input></td>
<td><input type="text" id="engine" value="<?php echo $row['Car_Engine_No'];?>"></input></td>
<td><input type="text" id="date" value="<?php echo $row['Date'];?>"></input></td>
<td><input type="text" id="mechanic" value="<?php echo $row['Mechanic'];?>"></input></td>
<td><input type="submit" name="submit" value="Change"/></td>
</tr>
</form>
<?php
}
?>
Here, each row of data has a corresponding button which will be used for changing or modifying the records of that particular row. Once the admin changes a specific appointment it should get updated in database.
My problem is, all the rows are getting generated by a while loop. Now how can I access a specific row when the change button of that specific row has been clicked ? As the rows are getting generated by a loop, I wont be able to access them bynameoridbecause all of them will have the samenameandid`.
Searched for relevant questions but none of them matched with my scenario. It will be of great help getting an answer. Thanks in advance.
Personally I'd be inclined to take the output from being in the loop for better control over the data and resolving the issue. You're also creating a new form on each loop.
Just loop the DB and create a new variable, then use that variable to output the data in the form.
Example code to show the basic idea, not tested or stating it's complete etc:
while ($row = mysqli_fetch_assoc($result)) {
$someNewVar[$row['id']] = $row;
// The 'id' index would be from DB which identifies individual rows
}
?>
<form action="adminEdit.php" method="POST">
<?php
foreach ($someNewVar as $index => $value) {
?>
<tr>
<td>
<input
type="text"
id="<?php echo $index;?>"
value="<?php echo $value['Name'];?>">
</input>
</td>
<td>
<input
type="submit"
name="submit"
value="Change"/>
</td>
</tr>
<?php
}
?>
</form>
Then you'd need to have the row ID passed from clicking the submit button.
On a side note, this whole approach could be tidied up, and data should be obtained in one file separate to where you output it.
Then in the file which obtains the data you can set the array to something which is also identified in the output file to manage if no data was obtained.
ie
getData.php
while ($row = mysqli_fetch_assoc($result)) {
$dataFromDb[$row['id']] = $row;
}
$someNewVar = !empty($dataFromDb) ? $dataFromDb : false;
showData.php
if ($someNewVar) {
// do the loop and form
} else {
echo 'sorry no data found';
}
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";
I have this code to show my table:
<form action="<?php echo $_SERVER['PHP_SELF'] ?>" method="POST">
<table cellspacing='0'>
<?php
if(isset($_GET["ordem"])){
if($_GET["ordem"] == 'descendente'){
echo "<thead><tr><th><a title='Ordenar por título' href='visualizarVoucher.php'>Utilizador</a></th>";
echo "<th>Email</th>";
echo "<th>Voucher</th>";
echo "<th>Categoria</th>";
echo "<th>Preço</th>";
echo "<th>Confirmação</th>";
echo "<th>Enviar mail</th>";
echo "</tr></thead>";
}
elseif($_GET["ordem"] == 'ascendente'){
echo "<thead><tr><th><a title='Ordenar por título' href='visualizarVoucher.php?ordem=descendente'>Utilizador</a></th>";
echo "<th>Email</th>";
echo "<th>Voucher</th>";
echo "<th>Categoria</th>";
echo "<th>Preço</th>";
echo "<th>Confirmação </th>";
echo "<th>Enviar mail</th>";
echo ("</tr></thead>");
}
}
else{
echo "<thead><tr><th><a title='Ordenar por título' href='visualizarVoucher.php?ordem=ascendente'>Utilizador</a></th>";
echo "<th>Email</th>";
echo "<th>Voucher</th>";
echo "<th>Categoria</th>";
echo "<th>Preço</th>";
echo "<th>Confirmação</th>";
echo "<th>Enviar mail</th>";
echo("</tr></thead>");
}
while($stmt->fetch()){
echo("<tbody>");
echo("<tr><td>$nomeUser</td>");
echo("<td>$email</td>");
echo("<td>$nomeVoucher</td>");
echo("<td>$categoria</td>");
echo("<td>$preco</td>");
echo("<td>$confirmacao</td>");
$content = file_get_contents($file,$filePDF);
echo("<td><INPUT TYPE='checkbox' NAME='mail[]' multiple='yes'></td>");
echo("</tr>");
echo("</tbody>");
}$stmt->close(); ?>
I have a checkbox in my table and I would like to know how can I get the values of each rows from the table when i selected the checkbox. I want to send email when the user selected multiple checkbox.
Thanks
It's possible that the code above is a snippet of a larger page, but if not:
You aren't actually wrapping your input elements in an HTML form tag. Doing so will cause the user agent (presumably a browser) to treat each input tag as something to be submitted to your backend form.
You should wrap the tables in a table element; tbody is a child of a table.
Regardless of the above:
It looks like your PHP code above will render the entire tbody each time the statement fetches a new row, which is a bit weird. I'd assume you only want to render a row containing mail options?
To the best of my knowledge, there is no multiple attribute allowed in a checkbox element. You may be thinking of the select element.
You are not setting a value attribute on your checkbox input tag. If the user actually submits a form, you'll either get a set of empty mail[] variables, or nothing at all, I'm not actually sure which.
Consider the code below: Note that the checkboxes have the same name attribute, but different values.
<form method="post">
<table>
<tbody>
<tr>
<td>
<input type="checkbox" name="mail[]" value="val1" id="mail-val1" />
<label for="mail-val1">Value 1</label>
</td>
</tr>
<tr>
<td>
<input type="checkbox" name="mail[]" value="val2" id="mail-val2" />
<label for="mail-val2">Value 2</label>
</td>
</tr>
<tr>
<td>
<input type="checkbox" name="mail[]" value="val3" id="mail-val3" />
<label for="mail-val3">Value 3</label>
</td>
</tr>
</tbody>
</table>
<input type="submit" />
</form>
Given this form, if the user selects all three of the checkboxes and submits, your server will receive a POST request with the payload:
mail[]=val1&mail[]=val2&mail[]=val3
Depending on how PHP parses that response (it's been about a decade since I've dealt with PHP), you'll probably have an array variable accessible to your application:
# mail == ["val1", "val2", "val3" ]
Hope this helps.
So this is the second assignment in a beginner PHP class. One part of the assignment requires you to allow the user to enter in multiple walls in an HTML form (the program is a calculator to figure out the cost of paint, labor, etc.), however you don't know how many walls the person is going to enter, so the form needs to be dynamic.
I don't think we're allowed to use javascript.
I've tried to use the SESSION variable to store the values into an array ( how to store variable values over multiple page loads ) and use foreach functions to loop and save the data ( How to store values from foreach loop into an array? ).
Nothing seems to be working. In this assignment we're not supposed to use SQL.
Is there another way to store an array? I'd also be happy with a way to echo the data and leave it there until the cache is cleared.
Here's the code I have right now (sorry it's a bit of a mess):
print_r($_POST);
echo "<br />";
print_r($_REQUEST['wallW']);
echo "<br />";
echo "<br />";
$wallW = $_REQUEST['wallW'];
echo "The width is $wallW.";
echo "<br />";
print_r($wallW);
$_SESSION['wallW'] = $wallW;
$wallW = $_SESSION['wallW'];
?>
<form name="getOrderInfo" action="" onsubmit="" method="post">
<table id="wallInfo">
<th>
Order Information
<th>
<tr>
<td>
Wall Width:
</td>
<td>
<input type="text" name="wallW[]" id="wallW" size="20" value="">
</td>
<tr>
<tr>
<td>
Wall Length:
</td>
<td>
<input type="text" name="wallL[]" id="wallL" size="20" value="">
</td>
<tr>
</table>
<input type="submit" value="Add Wall">
</form>
Any help would be great.
Thanks,
Chelsea
Do you use session_start(); on the top of the file, then $_SESSION['array'] = $array;.
store
$data = $_POST;
$_SESSION['data'] = $data;
and check on next page
if(isset($_SESSION['data'))
{
$data = $_SESSION['data'];
print_r($data);
}