update mysql datarow from php form with button - php

I am trying to update a php form that holds a few rows of mysql data. I have a button next to each row and when i click on that I want to update the row. The issue im having below is the ID is only set as the last row. How do i get this to push the ID to the button? So basically no matter what button i press i always get the same ID which is the last one to load.
if($result){
while($row = mysqli_fetch_array($result)){
$id = $row["ID"];
$beername = $row["BeerName"];
$beertype = $row["BeerType"];
$beerpercent = $row["BeerPercent"];
$beerdescription = $row["BeerDescription"];
$nowpouring = $row["NowPouring"] =='0' ? '' : 'checked=\"checked\"';
$glutenreduced = $row["GlutenReduced"] =='0' ? '' : 'checked=\"checked\"';
$beertogo = $row["BeerToGo"] =='0' ? '' : 'checked=\"checked\"';
echo "<form action='' method='POST'>";
echo "<tr><td><h6><input type=\"text\" size=\"5\" name=\"id\" value=\"$id\"></h6></td>";
echo "<td><h6><input type=\"text\" size=\"30\" name=\"BeerName\" value=\"$beername\"></h6></td>";
echo "<td><h6><input type=\"text\" size=\"30\" name=\"BeerType\" value=\"$beertype\"></h6></td>";
echo "<td><h6><textarea size=\"90\" style=\"width:250px;height:150px;\" name=\"BeerDescription\" value=\"\">$beerdescription</textarea></h6></td>";
echo "<td><h6><input type=\"text\" size=\"5\" name=\"Percent\" value=\"$beerpercent\"></h6></td>";
echo "<td><h6><input type=\"checkbox\" name=\"NowPouring\" value=\"true\" $nowpouring></h6></td>";
echo "<td><h6><input type=\"checkbox\" name=\"GlutenReduced\" value=\"true\" $glutenreduced></h6></td>";
echo "<td><h6><input type=\"checkbox\" name=\"BeerToGo\" value=\"true\" $beertogo></h6></td>";
#echo "<td><h6> <a href=\". $_SERVER["PHP_SELF"] .?id=".mysql_result($result,$j,'id')."\" onclick=\"\"></h6></td>";
echo "<td><h6> <button name=\"submit\" type=\"submit\" value=\"$id\">Save</button></h6></td>";
echo "</tr>";
echo "</form>";
}
}
if (isset($_POST['submit'])) {
$user = $_POST['submit'];
echo "<p style=\"color:#ffffff\">$id</p>";
#$delet_query = mysqli_query($mysqli, "UPDATE NowPouring SET NowPouring = '1' WHERE ID = '4'") or die(mysql_error());
if ($delet_query) {
echo '<p style="color:#ffffff">Beer with id '.$id.' is updated. To refresh your page, click ' . ' <a href=' . $_SERVER["PHP_SELF"] . ' > here </a></p>';
}
}
?>

The main problem I see here is that the while loop your code has is generating the same name for the inputs...
All of your "<button name=\"submit\" type=\"submit\" value=\"$id\">Save</button>" will have the same name, that's why it always has the last id as value.
Maybe you should try something such as..
<button name=\"$id_submit\" type=\"submit\" value=\"$id\">Save</button>
or if you want you can store it in an array..
<button name=\"submit[]\" type=\"submit\" value=\"$id\">Save</button>

You are seeing this result because the 'name' of each of your inputs is the same, so essentially you have a form with a bunch of elements that have the same names. You need to add a dynamic aspect to each name.
For example, you could update your output to something like this:
echo "<tr><td><h6><input type=\"text\" size=\"5\" name=\"id_$id\" value=\"$id\"></h6></td>";
Where each line adds the current id. Then when you retrieve the form data, you can append the submitted id to the field you want to update.
Have you considered using an AJAX approach so you can submit just the line in question and not have to reload the page and return the whole data set each time?

Make <form> for each submit button. Adding <form> in the while():
if($result){
while($row = mysqli_fetch_array($result)){
echo "<form action='' method='POST'>";
//...
echo "</form>";
}
}

Your form tag is placed at the wrong place.
It should be within:
while($row = mysqli_fetch_array($result)){
$id = $row["ID"];
//....
//....
echo "<form action='' method='POST'>";
echo"<tr>";
echo "<td>" . $id . "</td>";
//....
//....
echo "<td><button type='submit' name='submit'>Save</button></td>";
echo"</tr>";
echo "</form>";
}

Related

Handling Nested Forms in HTML/php

I try to figure out how to handle two nested forms. The first one sends data from select-option dropdown to another_file.php. The nested one should send data from check boxes to current file and should be handled by isset($_POST['...']). Here is my simplified code:
if (isset($_POST['a']))
{
// do something
}
if (isset($_POST['b']))
{
// do something else
}
echo "<form action='another_file.php' method='post'>"; // begin of first form
echo "<table class ='table table-hover table-condensed table-striped table-bordered'>";
echo "<thead>";
echo "<th>ID</th><th>Jídlo</th><th>Množství</th><th>por_cislo</th><th>Odebrat</th>";
echo "</thead>";
while($rows = $stmt->fetch()){
echo "<tr><td>" . $rows['id'] . "</td><td>".$rows['jidlo'];
echo "<select name =".$rows['id']."_".$rows['por_cislo']."> ";
$stmt2 = $db->query($q2);
echo "<option value ='nic'> (vyberte potravinu) </option>";
$max_por_cislo = $rows['por_cislo'];
while($rows2 = $stmt2->fetch())
{
echo '<option value="'.$rows2['id'].'">'.$rows2['jidlo'].'</option>';
};
echo "</select>";
echo "</td> <td>" . $rows['mnozstvi'] . "g <input name = '".$rows['por_cislo']."' type='text' value = '-'></td><td>".$rows['por_cislo']."</td>";
echo "<td><form action ='this_file.php' method = 'post'>"; // begin of nested form
echo "<input type='checkbox' id='atur_peg' name='idecko[]' value=".$rows['id']."*".$rows['por_cislo']." /></td></tr> ";
};
echo "<input type='hidden' name='pc' value=".$plan_cislo.">";
echo "<tr><td colspan='2'><input name = 'go' type='submit' value='OK'/></td><td colspan='2'><input type = 'submit' name ='a' value='ADD'/></td>";
echo "<td><input type = 'submit' name ='b' value='DELETE checked'/></form></td></tr>"; // end of nested form
echo "</table>";
echo "</form>"; // end of first form
Is
there any way to do this correctly?
Instead of nested forms, use jquery to detect checkbox being checked and then change the form action url. Something on this line.. You will have to modify the same to suit your needs.
$(document).ready(function(){
$("#formname").on("change", "input:checkbox", function(){
if( $(this).is(":checked") ) {
$('#formName').attr('action', 'this_file.php');
$("#formname").submit();
}
});
});

Delete individual lines/rows with PHP button

What I am trying to do is have a PHP page display the contents of a MySQL database and and each line it displays, it give me a delete button so I can delete individual rows. I have the code kind of working. The code delete the lines of code, but not the one I select, instead it deletes the last line and not the one I tell it to delete.
Here is a screenshot, I know it does not look pretty, I was going to clean it up after I get the code working.
HTML:
<?php
// Delete php code
if(isset($_POST['delete_series']))
{
// here comes your delete query: use $_POST['deleteItem'] as your id
$delete = $_POST['delete_series'];
$delete_sql = "DELETE FROM `Dropdown_Series` where `id` = '$delete'";
if(mysql_query($delete_sql, $conn))
{
echo "Row Deleted </br>";
echo "$delete";
};
}
//Insert Code
if(isset($_POST['add_series']))
{
$insert_sql = "INSERT INTO dropdown_series (series) VALUES ('$_POST[add_series]' )";
if(!mysql_query($insert_sql, $conn))
{
die ('Error: ' . mysql_error());
}
echo "Series Added <br><br>";
}
?>
<br />
<h1>Add New Series Title</h1>
<h3>Add New: </h3><br />
<form name = action="add_series.php" method="POST">
<input type = "text" name = "add_series" required/><br /><br />
<input type ="submit" name="submit" value="Add">
</form>
<h3>Current Series: </h3><br />
<?php
//Delete button on each result of the rows
$query = mysql_query("SELECT id, series FROM Dropdown_Series"); // Run your query
// Loop through the query results, outputing the options one by one
echo "<form action='' method='POST'>";
while ($row = mysql_fetch_array($query))
{
echo $row['series'] . " ";
echo $row['id'];
echo "<input type='hidden' name='delete_series' value=' " . $row['id'] . "' />";
echo "<input type='submit' name='submit' value='Delete'>";
//echo $row['series'] . " ". $row['id'] . "<input type='submit' value='delete'>";
echo "<br />";
}
echo "</form>";
?>
Your loop will result in multiple delete_series inputs - within the same form.
You could create separat forms for each option:
while ($row = mysql_fetch_array($query))
{
echo "<form action='' method='POST'>";
// ...
echo "<input type='hidden' name='delete_series' value=' " . $row['id'] . "' />";
echo "<input type='submit' name='submit' value='Delete'>";
// ...
echo "</form>";
}
I believe that a very quick answer would be
while ($row = mysql_fetch_array($query))
{
echo "<form action='' method='POST'>";
echo $row['series'] . " ";
echo $row['id'];
echo "<input type='hidden' name='delete_series' value=' " . $row['id'] . "' />";
echo "<input type='submit' name='submit' value='Delete'>";
//echo $row['series'] . " ". $row['id'] . "<input type='submit' value='delete'>";
echo "<br />";
echo "</form>";
}
If I were you I would prefer injecting some javascript in the logic, and perform the Delete request using an ajax call.
you can refer to this tutorial to get more understanding of what I am refering to https://scotch.io/tutorials/submitting-ajax-forms-with-jquery

How to pass a textbox value in to url parameter

i have some problem in here. I have textbox value inside table, and when i clicked link "Valid", i can pass the textbox value to another page.
This is my textbox code in table
echo "<form name='nomor' role='form' method='get'>";
echo "<input type='text' name='nomortempat' class='form-control input-sm'></input>";
echo "</form>";
This is my button
echo "<td class='center'>";
echo "<a class='btn btn-primary btn-sm' href='validasi.php?idorder=" . $row['id_order'] . "&pilih=" . $_GET['pilih'] . "'>
<i class='fa fa-check-square-o'>Valid</i></a>
echo "</td>";
Maybe someone can give me a solution, Thank you and have a nice day!!
In the page validasi.php add this:
$IDorder = $_GET['idorder'];
$Pilih = $_GET['pilih'];
Now you have two variables on validasi.php called IDorder and Pilih from your form
Or is it the nomortempat you want?
I think you can just add
$nomortempat = $_GET['nomortempat'];
to the validasi page and it should work. If I understand your code it should be sent
EDIT I was wrong, you need to add a sumbmit button to your form.
Add session start at the top of your pages: session_start();.
Then add this to your first page:
$_SESSION["idorder"] = $idorder;
$_SESSION["pilih"] = $pilih;
Then this code to your form:
echo "<form name='nomor' role='form' method='get'>";
echo "<input type='text' name='nomortempat' class='form-control input-sm'></input>";
echo "<input type='submit' name='submit' value='Submit'></input>";
echo "</form>";
Then on validasi page add this:
$nomortempat = $_GET['nomortempat']; // and:
$IDorder = $_SESSION["idorder"];
$Pilih = $_SESSION["pilih"];
Now you have all three values on validasi.php
with GET form, you could try this:
echo "<form name='nomor' action='action.php' role='form' method='get'>";
echo "<input type='text' name='nomortempat' class='form-control input-sm'></input>";
echo "<input type='submit' value='valid'>";
echo "</form>";
and in action.php page, to catch value in textbox name='nomortempat', code is below:
if (isset($_GET['nomortempat'])){
echo $_GET['nomortempat'];
}
Of course, you could add more input fields whenever you want to inside form with different names.

Executing PHP if a link is clicked

I've been searching around the internet, and of course Stackoverflow for answers on how to execute a PHP command when a link is clicked. Here is some basic code I have that's trying to either 'Update' or 'Delete' the data within the form.
if(isset($_GET['Delete'])){
$sql = "DELETE FROM addresses WHERE id ='$_POST[id]'";
mysql_query($sql,$conn);
header("Location: form.php");
};
if (isset($_GET['update'])){
$sql = "UPDATE addresses SET firstname='$_POST[firstname]', lastname='$_POST[lastname]', age='$_POST[age]' WHERE id='$_POST[id]'";
mysql_query($sql,$conn);
header("Location: form.php");
};
?>
<?php
while ($row = mysql_fetch_array($retreve, MYSQL_ASSOC)) {
echo "<form action=form.php method=post>";
echo "<tr>";
echo "<td><input type=text name=firstname value={$row['firstname']}> </td>";
echo "<td><input type=text name=lastname value={$row['lastname']}> </td>";
echo "<td><input type=text name=age value={$row['age']}> </td>";
echo "<td><input type=hidden name=id value={$row['id']}> </td>";
//links insead of buttons
echo "<td><a href = # id='update'> Update</a></td>";
echo "<td><a href = # id='delete'> Delete</a> </td>";
}
I have above the functions I'm trying to call whenever I click the links "Update" and "Delete". What am I suppose to do in order to get the PHP to execute.
NOTE: The database connection is not shown but it is connected.
echo "<td><a href = 'form.php?type=delete&id=99' id='delete'> Delete</a> </td>";
{$row['id']} for 99 in your particular case
then:
if($_GET['type']=='delete'){
$sql = "DELETE FROM addresses WHERE id ='$_GET[id]'";
mysql_query($sql,$conn);
header("Location: form.php");
}elseif ($_GET['type']=='update'){
//
}
if you are using the same form then check for your form method.Your form method is post an your conditions contains $_GET['Delete'] change it to $_POST['Delete']

HTML button running out of alignment

My idea is very simple, I will have a search box and a submit button.
When user key in the keyword and click on the submit button, results will be shown below with an additional button. Now my problem is I have no idea on how to make the button to be located at bottom right of the table populated.
Please consider the below code for my situation:
<input type="text" name="criteriaInput" style="width: 300px;"> <input type="submit" name="submit" value="GO" />
<?php
if (isset($_POST['submit'])) {
if(isset($_POST['inquiryMethod'])){
error_reporting(0);
$sql = 'SELECT
*
FROM
table
WHERE
fullname REGEXP \''.$_POST['criteriaInput'].'\'' ;
$server = mysql_connect("localhost","root", "");
$db = mysql_select_db("mysql",$server);
$query = mysql_query($sql);
echo "<table class=\"striped\">";
echo "<tr class=\"header\">";
echo "<td>Full Name</td>";
echo "<td>ID</td>";
echo "<td>ID Type</td>";
echo "<td>Issuance Country</td>";
echo "<td>Class</td>";
echo "</tr>";
while ($row = mysql_fetch_array($query)) {
echo "<tr>";
echo "<td>".$row[fullname]."</td>";
echo "<td>".$row[id]."</td>";
echo "<td>".$row[id_type]."</td>";
echo "<td>".$row[issuance_country]."</td>";
echo "<td>{$row['class']}</td>";
echo "</tr>";
}
echo "<form method=\"post\" action=\"CIF_InquiryAction.php\">";
echo "<input type=\"submit\" name=\"create\" value=\"Create\" />";
echo "</form>";
echo "</table>";
}else{
echo "Please select one of the criteria!";
}
}
?>
The submit button with value "Create" did successfully created on existence of data, however it's aligned on top left of the table.
Kindly advice Thank you.
You need to put your button into a table row and cell.
echo "<tr>";
echo "<td colspan=\"5\">"
echo "<form method=\"post\" action=\"CIF_InquiryAction.php\">";
echo "<input type=\"submit\" name=\"create\" value=\"Create\" />";
echo "</form>";
echo "</td>"
echo "</tr>";
Also, your form should probably move to be outside your table.
Editing to show input outside of table:
echo "</table>";
echo "<input type=\"submit\" name=\"create\" value=\"Create\" />";

Categories