Can't pass form data to PHP to update Database - php

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)

Related

How to prompt for button press confirmation?

I'm loading data in to a html table using following function. It also creates a delete button in front of each row. I want to prompt user to either confirm or cancel. But the code does not work and it does not prompt for confirmation. Can someone show me how to do it properly?.
I use (onclick="return confirm('Are you sure?')") to prompt.
//This function will list categories
function listCategories($sqlString)
{
$result = mysqli_query($this->connectToDb(), $sqlString);
if(mysqli_num_rows($result) > 0)
{
while ($row = mysqli_fetch_assoc($result))
{
echo "<tr>";
echo "<td>".$row['cat_id']."</td>";
echo "<td>".$row['it_category']."</td>";
echo '<td>
<form action="" method="POST">
<input type="hidden" name="catid" value="'.$row['cat_id'].'">
<input class="btn btn-outline-success" type="submit" name="Delete" value ="Delete" onclick="return confirm('Are you sure?')">
</form>
</td>';
echo "</tr>";
}
}
}
You need to escape the quotes around Are you sure. They're matching the quotes around the string argument to echo.
echo '<td>
<form action="" method="POST">
<input type="hidden" name="catid" value="'.$row['cat_id'].'">
<input class="btn btn-outline-success" type="submit" name="Delete" value ="Delete" onclick="return confirm(\'Are you sure?\')">
</form>
</td>';

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>

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.

PHP getting selected table rows from checkboxes

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.

Form in Form is not allowed, but what else

I fetch SQL data with a while loop and insert the data into a table. With a form and a submit button i can save modified values.
My simplified code:
<table>
<tr>
<?php
//SQL QUERY
//...
while ($row = mysql_fetch_array($sql_header)) {
$var_ab = $row['ab'];
$var_id = $row['id'];
?>
<form id="form1" action="" method="POST">
<td>
<input type="text" value="<?php echo $var_ab; ?>"
</td>
<td>
<input type="text" value="<?php echo $var_id; ?>"
</td>
//PLACEHOLDER FOR SECOND FORM
<?php
}
?>
</tr>
<td>
<input type="submit" name="save" value="SAVE" class="classsubmit" />
</td>
</form>
</tr>
</table>
So far, so good. So, how can I insert a second form to delete an entry? I've tried to place this code (PLACEHOLDER FOR SECOND FORM - see above)
<td>
<form id="form2" action="" method="POST">
<input type="text" value="<?php echo $var_id;?>"
</form>
</td>
but it's not working and it's not allowed to nest forms.
Any suggestions?
If you only want to delete an entry on the page or in the database you could try a button or a span with an onclick function.
for example:
<span onclick="window.location='?delete=<?php echo $row[(unique-value-in-database-from-this-row)]; ?>'; return false">Delete entry</span>
Make sure you add return false or the first form will be submitted. If you use a button make sure it has type="button"
On this page could be a PHP code like this:
if(isset($_GET['delete']))
{
$item = $_GET['delete'];
//SQL connect
$result = mysql_query($conection ,"DELETE FROM table WHERE uniquevalue='$item'");
}
I hope gives an idea for a solution.

Categories