PHP getting selected table rows from checkboxes - php

I have a PHP form where a table is created of all files in a folder on the server, and each row created is assigned a checkbox which will be used to decide which files are to be deleted or shared etc. Each row is given a name checkbox[$rownumber] to distinguish each, and then when a button is clicked, for the moment to ensure I can get it working, it just prints the rows that are selected - but I can't get this working.
Initially, as rows are created in the table from the server, this is the code, which correctly creates them as I wish
<?php
if(isset($_REQUEST['deleteFile']))
{var_dump($_REQUEST);
if(isset($_POST['checkbox']))
{
print_r($_POST);
}
}
?>
<form name="mainHomescreen" action="MainHomescreen.php" method="POST">
<nav>
<input type="text" name="Search" value="Search" style = "color:#888;" onFocus="inputFocus(this)" onBlur="inputBlur(this)"/>
</nav>
<sidebar>
<input type="button" value="Create Folder" onClick="createFolder()"/>
<input type="button" value="Download Selected Files/Folders" onClick=" "/>
<input type="button" value="Encrypt Selected" onClick="encrypt()"/><br>
<input type="button" value="Share Selected" onClick="shareFolder()"/>
<!-- upload a file -->
<div id="fileUpload">
<div id="uploadPopup">
<form action="<?php echo $_SERVER['PHP_SELF']; ?>" id="uploadForm" method="post" name="uploadForm" enctype="multipart/form-data">
Select file to upload: <input name="fileUpload" type="file" /><br />
<input type="submit" value="Upload File" name="submitFile"/>
</form>
</div>
</div>
<input type="button" name="upload" value="Upload File" onClick="showUpload()"/>
<input type="submit" value="Delete" name="deleteFile"/>
<input type="button" value="Rename" onClick=" "/><br>
<input type="button" value="Password Protect Folder/ File" onClick=" "/><br><br>
</sidebar>
<article>
<span class="error"><?php echo $error;?></span>
<table id="detailView" style="width:100%">
<!-- php to create table -->
<?php
//open file names
$dir = opendir("/home/a1962403/public_html/files");
$filearray = array(array(array()));
echo '<table cellpadding="10" cellspacing="0" style="width:100%">';
echo '
<tr>
<th> </th>
<th>File</th>
<th>Date</th>
<th>Size</th>
</tr>
';
$rownumber = 0;
//List files in directory
while (($file = readdir($dir)) !== false)
{
//gets the file date, string needed decoding otherwise throws error.
$date = #filemtime($file);
$date = date("F d Y H:i:s.", filemtime(utf8_decode("/home/a1962403/public_html/files/$file")));
$size = filesize("/home/a1962403/public_html/files/$file") . ' bytes';
$rownumber = $rownumber + 1;
//prints a table row
echo '<tr class="bottomline">';
echo "<td><input type='checkbox' name='checkbox[$rownumber]' value='[$rownumber]' </td>";
echo "<td>$file</td>";
echo "<td>$date</td>";
echo "<td>$size</td>";
echo '</tr>';
}
echo '</table>';
closedir($dir);
?>
</article>
</form>
</body>
</html>
From this, I have a submit button called 'deleteFile', which I am wanting to use to as I said for the moment, just get what is selected to ensure it works, but it's not actually giving me any output so any help would be greatly appreciated.

Your row formatting may be the problem
echo "<td><input type='checkbox' name='checkbox[$rownumber]' value='[$rownumber]' </td>";
Change it to:
echo "<td><input type='checkbox' name='checkbox[" . $rownumber . "]' value='". $rownumber . "' </td>";
And because your are numbering from 0 up you could also just use checkbox[] as a name.
It would help to this form live.

You are right to use isset when determining whether a checkbox is checked or not, but you are using differring names:
isset($_POST['checkbox'])
will return true if
<input type="checkbox" name="checkbox" />
is checked.
You have to refer to posted inputs using their names in the $_POST array.
In this case, you need to check for checkbox[$rownumber], which, as is seemingly trivial, requires you to know the row numbers when posting:
PHP code
if (isset($_POST["checkbox[$rownumber]"]))
{
// This checkbox is checked
}
If you don't know the exact input names, you might want to iterate through the $_POST array:
PHP code
foreach ($_POST as $input_name => $input_value)
{
if (strpos($input_name, 'checkbox') !== false)
{
// This input's name contains the substring 'checkbox'
}
}
Note the type-strict comparison at strpos.

Related

interface php and html, in foreach loop

I have a PHP page that shows me data from the database. I'm inserting a button that, if pressed, deletes the record. The problem is that if I push the button the action is done on all the records, because I can't uniquely identify the click on the button
some code
foreach ( $associati as $associato ) {
echo "<hr />";
echo "Nome associato : ".$associato->Nome."</br>";
echo "Codice Fiscale : ".$associato->CF."</br>";
echo "<hr />";
if(isset($_POST["numerazione"])){
echo "Hello world"; //Query for delete
}
?>
<form method="POST" action="">
<input type="submit"
name="numerazione"
value="Elimina utente"
onclick="return confirm('Are you sure?')"
/>
</form>
<?php
}
How can I do to uniquely identify the button?
You can add a hidden field to each form that contains the unique identifier of the data, that means when you click the button, it will create a POST request, and in that POST request you can get the ID of the clicked record by doing $_POST['unique-id'], also make sure to populate the value of that hidden field using PHP
<?php
foreach ( $associati as $associato ) {
echo "<hr />";
echo "Nome associato : ".$associato->Nome."</br>";
echo "Codice Fiscale : ".$associato->CF."</br>";
echo "<hr />";
if(isset($_POST["numerazione"])){
$numerazione = $_POST["unique-id"];
echo "Unique record is : ".$numerazione."</br>";
}
?>
<form method="POST" action="">
<input type="hidden" name="unique-id" value="<?php echo $associato->CF; ?>" />
<input type="submit"
name="numerazione"
value="Elimina utente"
onclick="return confirm('Are you sure?')"
/>
</form>
<?php
}
?>
Pass the unique information (e.g. $id or $associato->id or whatever the variable which can identify the record) when the form is submitted
<form method="POST" action="">
<input type=hidden name=id value=<?php echo $id; ?>>
<input type="submit"
name="numerazione"
value="Elimina utente"
onclick="return confirm('Are you sure?')"
/>
</form>
Solution for this problem:
if(isset($_POST["mod"]) and $_POST["id"]== $associato->ID ){
echo "Hello world";
}
?>
<form method="POST" action="">
<input type="hidden" name="id" value=<?php echo $associato->ID; ?>>
<input type="submit"
name="mod"
value="valore"
onclick="return confirm('Are you sure?')"
/>
</form>

Can't pass form data to PHP to update Database

Thanks to all who responded. I got it to update with a combination of ideas from you. I've amended the code to show what's working.
To implement LIKE functionality by passing the LIKE button value to php so as to update the DB.
This displays the table, complete with a LIKE button per row:
echo '<table>
<tr>
<th>Word ID</th>
<th>User ID</th>
<th>User Name</th>
<th>Word</th>
<th>Meaning</th>
<th>Example</th>
</tr>';
foreach ($data as $row)
{
echo '<tr>';
foreach ($row as $value)
{
echo '<td>';
echo $value;
echo '</td>';
}
echo '<td>
<form method="POST" action="'.$_SERVER["PHP_SELF"].'">
<input type="hidden" name="LIKE" value="'.$row['wordID'].'">
<input type="submit" class="btn btn-success" value="Submit">
</form>
</td>';
echo '</tr>';
}
echo '</table>';
The code to process the form submit is:
if($_POST['submit'])
{
$sql = "UPDATE vocab SET likes = likes+1 where wordID = '{$row['wordID']}'";
$stmt = $db->prepare($sql);
/* Execute */
$stmt->execute();
}
<form method="post" action="<?php echo $_SERVER["PHP_SELF"]?>
is a sytax you use when you are NOT already in a <?php tag. Here, you already are writing in PHP and in an echo and you just apen again a <?php, and another echo in it, this makes no sense.
echo '... <form method="post" action="'.$_SERVER["PHP_SELF"].'"> ...';
is the way you want to include your php_self value.
also
<input type="submit" value="LIKE" name="<?php echo $row["wordID"]; ?></form>
should be
<input type="submit" value="LIKE" name="'.$row['wordID'].'"></form>
but you cant the search for $_POST['wordID'], search for $_POST[$row['wordID']] in a for loop.
You're doing an echo inside an echo here :
echo '<td>
<form method="post" action="<?php echo $_SERVER["PHP_SELF"]?>
<input type="submit" value="LIKE" name="<?php echo $row["wordID"]; ?></form>
</td>';
<form method="post" action="<?php echo $_SERVER["PHP_SELF"]?>
should be :
<form method="post" action="'.$_SERVER["PHP_SELF"].'">
i would do this:
<td>
<form method='POST'>
<input type='hidden' name='LIKE' value='".$row['wordId']."'>
<input type='submit' value='Submit'>
</form>
</td>
Action will always default to : PHP_SELF so no point adding that, additionally adding the hidden field instead of the submit button is preferable to me as it's easier to read, plus adds an easy option incase you actually want to add more to the form (which is entirely possible)

Implementing checkbox header

I have a code which retrieves data from db and show it to a table. It is working fine but I want to implement a checkbox as part of the header which would allow me to select/deselect all rows. The header is just being pulled from db comments so I have no idea on how to implement the checkbox-select/deselect all header.
Here is my code,
<div>
<form action="test4.php" method="post"><?php
if(is_array($result)){
echo '
<fieldset>
<legend>Assign</legend>
<div>Changes will affect selected rows only.</div>
<table width=auto cellpadding=1px cellspacing=0px border=1 align=center>
<thead>
<tr>';
// column comment from DB as column header
foreach($result[0] as $key => $val){
echo '<th>'.$colcomments[$key].'</th>';
}
echo '
</tr>
</thead>
<tbody>';
foreach($result as $row => $info){
echo '
<tr>';
foreach($info as $key => $val){
if($key=='id'){
echo '
<td title="'.$colcomments[$key].'">'.$val.'.
<input type="checkbox" name="'.$key.'['.$info['id'].']"
value="'.$val.'" id="rowid_'.$val.'" />
<label for="rowid_'.$val.'"></label></td>';
}
else {
echo '
<td title="'.$colcomments[$key].'">
<input type="text" name="'.$key.'['.$info['id'].']"
value="'.$val.'" />
</td>';
}
}
echo '
</tr>';
}
echo '
</tbody>
</table>
</fieldset>';
}
?>
<fieldset>
<legend>Select Date</legend>
<div>Select Date from and Date to</div>
<input type="date" name="from" id="from" value="<?=$date['from']; ?>" />
<input type="date" name="to" id="to" value="<?=$date['to']; ?>" />
<div><input type="submit" value="Submit" /></div>
</fieldset>
</form>
</div>
This is the my script for the checkbox, and I dont know where I can insert a code to create a checkbox header. This is different from the ones posted previously as my issue is how I can create a checkbox header, if i only used the commments section in my db to make it as the header.
<script>
jQuery(document).ready(function () {
jQuery("input[name=checkall]").click(function () {
jQuery('input[name=checkall]').prop('checked', this.checked);
jQuery('input[name=checkbox]').prop('checked', this.checked);
});
// if all checkbox are selected, check the selectall checkbox
// and viceversa
jQuery("input[name=checkbox]").click(function(){
if(jQuery("input[name=checkbox]").length == jQuery("input[name=checkbox]:checked").length) {
jQuery("input[name=checkall]").prop("checked", true);
} else {
jQuery("input[name=checkall]").prop("checked", false);
}
});
});
</script>
I'm marking this as resolved. Easy fix is just to set the type to hidden.
Change from
<input type="checkbox" name="'.$key.'['.$info['id'].']"
To
<input type="hidden" name="'.$key.'['.$info['id'].']"
Checkbox is just a redundant since I need to update all rows anyways.

how to get the submit button value which is in while loop using post method

Input field inside a while condition i'm displaying the tab in which tab values are fetched from table red_digid_info
<form method="POST" action="" id="form_isp_status" onsubmit="submit_isp_status('form_isp_status');"">
<div class="row">
<label for="fromdate" class="col-sm-1 control-label"> FROM DATE </label>
<label for="todate" class="col-sm-1 control-label" style="margin-left: 4cm;"> TO DATE </label>
</div>
<div class="row">
<div class="col-sm-1">
<div class="input-group">
<input type="text" class="form-control" id="fromdatepicker" name="fromdate" placeholder="yyyy-mm-dd" style="width:200px;height:33px;">
<span class="input-group-addon"><i class='glyphicon glyphicon-calendar'></i></span>
</div>
</div>
<div class="col-sm-1" style="margin-left:4cm">
<div class="input-group">
<input type="text" class="form-control" id="todatepicker" name="todate" placeholder="yyyy-mm-dd" style="width:200px;height:33px;">
<span class="input-group-addon"><i class='glyphicon glyphicon-calendar'></i></span>
</div>
</div>
<div class="col-sm-offset-2 col-sm-2">
<input type="submit" value="ISP Status" class='btn btn-purple btn-rounded w-md m-b-5' name="isp_button">
<input type="hidden" value="1" name="pointer">
<button type="button" class="btn btn-pink btn-rounded w-md m-b-5" onclick="resetforms('form_isp_status')">Reset</button>
</div>
</div>
<div class="row">
<label for="isp" class="col-sm-1 control-label"> SELECT ISP</label>
</div><div class="row">
<div class="tab">
<?php
$isp_tab = mysql_query("SELECT DISTINCT(`isp`) FROM `red_dgid_info`");
while ($result = mysql_fetch_array($isp_tab)) {
$isp_value = $result[0];
echo '<input class="tablinks ion-social-rss" type="submit" name="isp_value[]" value="'.$isp_value.'">';
//echo '<input type="hidden" name="isp_hidden_value[]" value="'.$isp_value.'">';
}
?>
</div>
</div></form>
if i click any one value of a tab i ve to display the tab content so i need the value of submit button in php post method
if($_REQUEST['pointer'] ==1)
{
var_dump($_POST);
//-------status criteria given---------------------//
//-----------isp tab submiited--------------//
if(isset($_POST['isp_value']))
{
print_r($_POST['isp_value']);
$isp=$_POST['isp_value'];
}
//------------------end----------------------//
//----------hidden value array--------------//
/*$data = $_POST['isp_hidden_value'];
foreach($data as $isp)
{
echo "isp_hidden =".$isp;
}
//---------------another way----------------//
$isp_hidden = $_POST['isp_hidden_value'][$isp];*/
//--------------end------------------------//
$date= date("Y-m-d");;
$fromdatepicker =$_POST['fromdate'];
$todatepicker =$_POST['todate'];
exit;
}
if(isset($_POST['isp_value'])) //this if condition fails isp_value is not set don't know the reason and solution for it
submit function
function submit_isp_status(formId) {
if($("#"+formId).valid() == true) {
$.ajax({
type: 'POST',
url: 'webxstatus.php', //same page
data: $("#"+formId).serialize(),
success: function(data) {
..........
}
});
}
}
I'm stuck with this for past 2 days anyone help me to solve this.
you need to change your input name to array like this isp_value[] so only you can get the value which submit button you clicked otherwise you will get last value only .
echo "<input class='tablinks ion-radio-waves' type='submit' name='isp_value[]' value='$isp_value'></input>"
PHP :
print_r($_POST['isp_value']);
And also minor single quotes problem in your isp_hidden_value
echo '<input type="hidden" name="isp_hidden_value[]" value="'.$isp_value.'">';
note:
if you need currently clicked submit button value means . don't use hidden field it will collect all values . just insert the value in submit button it will collect only curently clicked element value only as a array
Try this example :
<?php
if(isset($_POST['xyz']))
{
print_r($_POST);
}
?>
<form action="" method="post">
<input type="submit" name="xyz[]" value="1" >
<input type="submit" name="xyz[]" value="2" >
</form>
<?php $isp_tab=mysql_query("select distinct(isp) from red_dgid_info");
while($result=mysql_fetch_array($isp_tab))
{
echo'<form method="POST" action="" id="form_isp_status" onsubmit="submit_isp_status('form_isp_status');">';
$isp_value =$result[0];
echo "<input class='tablinks ion-radio-waves' type='submit' name='isp_value' value='$isp_value'></input>";
echo '<input type="hidden" name="isp_hidden_value" value='$isp_value'>';
echo'</form>';
}?>
put form inside while loop
while($result=mysql_fetch_array($isp_tab))
{
$isp_value =$result[0];
echo "<input class='tablinks ion-radio-waves' type='submit' name='isp_value' value='$isp_value'></input>";
echo '<input type="hidden" name="isp_hidden_value[]" value='$isp_value'>';
}?>
$data =$_POST['isp_hidden_value'];
foreach($data as $isp)
{
echo "isp_hidden"=$isp;
}
Use input field 'isp_hidden_value' as array and fetch values using foreach
You need to do some changes in your code, and after that i hope it will work perfectly:
Change hidden field
from:
echo '<input type="hidden" name="isp_hidden_value" value="$isp_value">';
to:
echo "<input type='hidden' name='isp_hidden_value[$isp_value]' value='" . $isp_value . "'>";
In the post method change value assignment of hidden field
from:
$isp_hidden = $_POST['isp_hidden_value'];
to:
$isp_hidden = $_POST['isp_hidden_value'][$isp];
Rest should work fine.
Logic behind this change is to use array when using same name for multiple input types. Here you are using a flat variable which will hold only one value, which will get assigned at the end. If you use array it will hold multiple values and allows you to get your desired result.
You don't need a hidden field for this. A button with a name should send it's value.
<?php
var_dump($_POST);
?>
<form method="POST" action="">
<div class="row">
<div class="tab">
<input type="submit" name="button" value="test1">
<input type="submit" name="button" value="test2">
</div>
</div> </form>
Will tell me that $_POST['button'] is either test1 or test2
Which means that the following should work
<form method="POST" action="" id="form_isp_status" onsubmit="submit_isp_status('form_isp_status');"">
<div class="row">
<div class="tab">
<?php $isp_tab=mysql_query("select distinct(isp) from red_dgid_info");
while($result=mysql_fetch_array($isp_tab))
{
$isp_value =$result[0];
echo "<input class='tablinks ion-radio-waves' type='submit' name='isp_value' value='$isp_value'>";
// note: input is a empty tag, meaning that it is not to be closed using </input> but by using />, which
// is only relevant for XHTML
}?>
</div>
</div> </form>
Edit:
On the server side the only thing you have to do is use the value of $_POST['isp_value'].
var_dump($_POST); // only to check the POST variable during debugging
if (isset($_POST['isp_value'])) { // Possibly not needed if there are no other submit buttons in the from, but good practice to check if something exists
// do something using $_POST['isp_value']
}
As a sidenote: mysql_* has been deprecated in PHP 5.5.0 and been removed in PHP 7.0. It is recommended to either use MySQLi or PDO instead

Modifying $i inside a form

so I have a form. The form consists of 10 lines by default. It goes like this:
<form method="post" action="actionhere">
<?php
for($i=0; $i<10;$i++) {
?>
<div class='clone_me'>
<span>Line <?php echo $i;?></span>
<input type='checkbox' name='ck_<?php echo $i;?>'/>
<input type='text' name='tx_<?php echo $i;?>'/>
</div>
<?php } ?>
<input type='submit' name='submit' value='Submit'/>
</form>
So inside the form, we will have 10 rows of checkbox+textbox.
What I'm trying to make is, I want to place a button to add new row (the checkbox+textbox). Now, problem is, I need the $i value (since it's form the for loop). Is that possible that when we click the add row button, the value of $i that we set inside for loop be incremented by 1 on each click? I know we can clone the div using jquery, but how about the $i value?
I think you are doing it in wrong way you do not need $i value inside name attribute you have to use array for it for example
<form method="post" action="test.php">
<div class='clone_me'>
<span>Line 1</span>
<input type='checkbox' name='ck[]'/><!--this field should menditory-->
<input type='text' name='tx[]'/>
<span>Line 2</span>
<input type='checkbox' name='ck[]'/><!--this field should menditory-->
<input type='text' name='tx[]'/>
</div>
<input type='submit' name='submit' value='Submit'/>
</form>
Now implement this code in actionhere.php
<?php
$cks = $_POST['ck'];
$txs = $_POST['tx'];
foreach($cks as $key => $ck) {
echo $ck."<br>";
echo $txs[$key]."<br>";
}
?>
Well, basically no. Your PHP script is already over when the html has been generated. So you can't rely anymore on PHP. But you don't need to make it explicitly appear in your html.
You should count the rows using jquery :
var i = $('form').find('.clone_me').length
and then add a new row using javascript again :
$('form .clone_me:last').clone().insertAfter('form .clone_me:last');
<input type='hidden' name='counter' id='counter'/>
<input type='checkbox' name='chk' id='chk'/>
<?php
$counter=$_POST['counter'];
for($i=0;$i<=$counter;$i++)
{
$chk=$_POST['chk'.$i];
// Your Insert Code Here
}
?>
may be this can be but have some limit
if you have no problem with page reload the you can do it is:-
by this way your page will reload and the value in textbox and checkbox will gone:---:)
every time new page generate and send by server to client browser
<?php
if(isset($_POST['submit'])){
$ends = $_POST['ttl_rows'];
}else{
$ends = 10;
}
?>
<form method="post" action="#">
<?php
for($i=1 ; $i<$ends;$i++) {
?>
<div class='clone_me'>
<span>Line <?php echo $i;?></span>
<input type='checkbox' name='ck_<?php echo $i;?>'/>
<input type='text' name='tx_<?php echo $i;?>'/>
</div>
<?php } ?>
<input type='hidden' name='ttl_rows' value='<?php echo ($i+1); ?>'/>
<input type='submit' name='submit' value='Submit'/>
</form>

Categories