Using HTML buttons in PHP loops - php

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

Related

Codeigniter, Passing Inputs of Array and then display the result

Excuse me if this question is already asked everywhere, but i cant find answer that worked.
So I have a dynamically generated table, which is generated by selecting rows from a table in a database.
This is the view file that create the table.
all rows except the heading are created based on how many data found in the table in a database, so, all the inputs are have name like
<form class="form-horizontal" role="form" id="formDtKryw" method="POST" action="updKryw">
<div class="table-responsive form-group row">
<table class="table table-hover table-condensed table-bordered">
<thead class="text-center">
<tr>
<th>No</th>
<th>Nama</th>
<th>Telepon</th>
</tr>
</thead>
<tbody>
<?php $no = 0;
foreach ($dftr_crKryw as $data_crKryw):
$no_ktp[$no] = $data_crKryw->no_ktp;
?>
<input type="hidden" name="no_ktp[<?php echo $no; ?>]" id="no_ktp[<?php echo $no; ?>]" value="<?php echo $data_crKryw->no_ktp; ?>">
<tr>
<td><?php echo $no+1; ?></td>
<td><?php $this->db->select('nama,')->from('dt_prbd')->where('no_ktp', $data_crKryw->no_ktp);
$qry = $this->db->get();
if ($qry->num_rows() > 0) {
foreach($qry->result() as $data):
echo $data->nama;
endforeach;
}
?></td>
<td><?php
if ($data_crKryw->memo == NULL) {
?>
<select class="form-control input-sm" name="memo[<?php echo $no; ?>]" id="memo[<?php echo $no; ?>]">
<option value="">---Pilih---</option>
<option value="Memo 1">Memo 1</option>
<option value="Memo 2">Memo 2</option>
<option value="Memo 3">Memo 3</option>
</select>
<?php
}
else {
echo $data_crKryw->memo;
}
?></td>
</tr>
<?php
$no++;
endforeach;
}
?>
<input type="hidden" name="totData" id="totData" value="<?php echo $no; ?>">
<tr>
<td colspan="11" align="right"><button type="submit" id="submit" class="btn btn-primary">Simpan Data</button> <button type="reset" class="btn btn-danger">Hapus Form</button></td>
</tr>
</tbody>
</table>
</div>
</form>
This is the Controller that should catch the inputs
function updKryw(){
$totData = $this->input->post('totData');
$no_ktp = $this->input->post('no_ktp');
$memo = $this->input->post('memo');
$frmUpdKryw = array(
'totData' => $totData,
'no_ktp' => $no_ktp,
'memo' => $memo
);
$this->load->view('display_data', $frmUpdKryw);
}
And this is the view file that suppose to view all the captured information from the form
<html>
<head></head>
<body>
<?php
for($x = 0; $x < $totData; $x++){
echo $totData . "<br>";
echo $no_ktp[$x] . "<br>";
echo $memo[$x] . "<br>";
}
?>
</body>
</html>
All that displayed is only the $totData, and the $no_ktp[$x] and $memo[$x] is not display anything.
Anyone can help please if there is any error in my code or my logic.
Thanks in advance.
=========================================================================
edit: i started to think that my php engine is broken. why?
even this simple form doesn't display anything.
form.php
<form name="myForm" method="post" action="go.php">
<input type="text" name="name" value="firstname">
<input type="text" name="addr" value="firstaddr">
<button type="submit" name="submit" id="submit">save</button>
</form>
go.php
$name = $_POST[name];
$addr = $_POST[addr];
echo $name;
echo $addr;
First I recommend debug before saving data to $frmUpdKryw array
$this->input->post(NULL, TRUE); // returns all POST items with XSS filter
$this->input->post(); // returns all POST items without XSS filter
Then if data is not empty, before
$this->load->view('display_data', $frmUpdKryw);
add
var_dump($frmUpdKryw);
if all is good here, then to debug in beginning of the view
var_dump($totData);
var_dump($no_ktp);
var_dump($memo);
If all is good here then problem is in your loop, so you will need just fix it. Either you will know where you have problems:
failed with sending data with POST
failed with saving to new variable
failed with sending data to view
and last failed with loop
Hope it will help
when I solve another problem within the same app, this problem is fixed too, the problem is not in the code or logic. all codes are works as expected.
here are the link for the solution. not the solution that I expect, but its working.
The Solution
thanks to Abdulla and Oleg Sapishchuk

get selected value in an auto populated drop down

I would like to know how we can store the value selected in an auto populated drop down (HTML5) into a variable, all in PHP. I want to obtain this value BEFORE clicking the 'Submit' button.
<?php
$i=1;
$j=0;
$result=pg_exec($pgsql_conn,"select * from crm.product_info order by 1");
while ($row = pg_fetch_assoc($result))
{
?>
<td><input type="checkbox"
id= <?php
echo $row['product_id'];
?>
value= <?php
echo $i;
?>
name= "prod[]">
<?php echo $row['product_name']; ?>
</td>
<td>
<input type="button" value=<?php echo "$".$row['product_value']; ?> id="but">
</td>
<td>
Quantity
<select class="select" name="qty[]">
<?php echo "qty".$j; ?>
</select>
</td>
<td>
Amount
<input
id="amt"
type="text"
readonly
value=<?php
echo $row['product_value']
?> >
</td>
<?php
}
?>
I require the SELECTED value of 'quantity'.
This is how i auto populate the quantity. It is from 0-100.
$(document).ready(function() {
for(i=0;i<=100;i++)
{
$(".select").append("<option value=\""+i+"\">"+i+"</option>");
}
});
First of all, PHP is server side, so it can't handle changes made in the browser until a request is send to it. You will have to use javascript to know selected value in real time before submitting the form. You can manipulate this value using javascript. But if you really need to do some PHP with the selected value, your solution is to use Ajax for this.

How to get the name/id of multiple buttons

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";

Why is my php form not generating values?

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

Looping through an array of checkbox

I have a form with rows which are populated from a table. Each row has a "checkbox" which the user can check or not.
When the form is submitted I want to be able to read which checkbox have been selected and insert the result in to a data table.
My code so far
FORM:
<form method="post" name="form1" action="<?php echo $editFormAction; ?>">
<table
<?php do { ?>
<tr>
<td>input type="text" name="InspectRoomNo" value="<?php print $row_InspectItems['AuditItemNo']; ?>"></td>
<td>php echo $row_InspectItems['AuditItem']; ?>td>
<td>input name="check[]" type="checkbox" ></td>
</tr>
<?php } while ($row_InspectItems = mysql_fetch_assoc($InspectItems)); ?>
<input type="submit" value="Insert record">
</table>
The insert: fetchs $Items from table
while($row = mysql_fetch_assoc($Items))
{
$array[] = $row['AuditItem'];
}
foreach($array as $id) {
$AuditItemID = mysql_real_escape_string($id);
if(isset($_POST['check'])){
$Checked = mysql_real_escape_string($_POST['check'][$row]);
}
}
The problem I am having is the returned values for all the checkbox is true, even if a checkbox was not selected.
Can anyone help me sort this issue.
Many thanks.
Do it like this:
if(!empty($_POST['check'])) {
foreach($_POST['check'] as $check) {
echo $check;
}
}
You should put the item id inside the checkbox name:
<td><input name="check[<?= $row_InspectItems['AuditItem']; ?>]" type="checkbox" /></td>
Then, you can simply iterate over it:
foreach ($_POST['check'] as $id => $value) {
// do stuff with your database
}
I'm assuming than whomever runs this script is trusted, because it would be easy to forge the list of ids; make sure the current user has permissions to update those records.
What is happening, is that only selected checkboxes get sent to the server, so you will see that your $_POST['check'] array (this is an array!) is smaller than the number of items you have displayed on the screen.
You should add your ID's so that you know what checkboxes got checked and adapt your php processing code to handle an array instead of a single value.
You are also overwriting your InspectRoomNo every row, so you should use an array there as well.
The form side would look something like:
<td><input type="text" name="InspectRoomNo[<?php echo row_InspectItems['AuditItemNo']; ?>]" value="<?php print row_InspectItems['AuditItemNo']; ?>"></td>
<td><?php echo $row_InspectItems['AuditItem']; ?></td>
<td><input name="check[<?php echo row_InspectItems['AuditItemNo']; ?>]" type="checkbox" ></td>

Categories