on edit fill the form fields with the database values - php

I have checkbox list in my form where user can select and save the data in to the database and edit the data.
In the checkbox list i have one checkbox named other and if user check the checkbox named other it populates a textbox in which user has to enter the other value.
while saving the data into the database I just replaced other checkbox value with textbox value.so upto now its working good.
But if user wants edit the form, I have to show the checkboxes with mark if value exists in the database and also if there is any value related to other then other checkbox should be checked and i have to place the value in the textbox.
Please find the code below
$aEquipment = array("Arthroscopy", "K-wires", "C-arm", "Mini-c-arm", "Other");
//converting comma separated into array using explode function
$dbequipment = $event->proc_equipment_request; //array of values from database
$dbequipment= explode('|',$dbequipment);
foreach ($aEquipment as $equipment) {
if(in_array($equipment,$dbequipment)) {
echo "<input name=\"equipment[]\" type=\"checkbox\" value=\"$equipment\" CHECKED> $equipment ";
} else{
if($equipment == "Other"){
echo "<input name=\"equipment[]\" type=\"checkbox\" id=\"otherEquipment\" value=\"$equipment\"> $equipment";
echo "<input type=\"text\" id=\"otherEquipmentVal\" name = \"otherEquipment\" style=\"display:none; width:25%;\" placeholder=\"Equipment request\" />";
} else {
echo "<input name=\"equipment[]\" type=\"checkbox\" value=\"$equipment\"> $equipment";
}
}
}
I am able to check the checkboxes but unable to place the value of textbox.

You need to fill the value attribute of the text field, you have now:
echo "<input type=\"text\" id=\"otherEquipmentVal\" name = \"otherEquipment\" style=\"display:none; width:25%;\" placeholder=\"Equipment request\" />";
And need to have:
echo "<input type=\"text\" id=\"otherEquipmentVal\" name = \"otherEquipment\" style=\"display:none; width:25%;\" placeholder=\"Equipment request\" value=\"Your Value\" />";
Note the difference is the follow attribute at the end:
value=\"Your Value\"

Related

Updating data in MySQL database based on checked dynamic checkboxes in the table

I'm sorry about my question, but I'm starting with PHP and I want to ask you for a help with my problem.
In my web application I work with a table, which has a dynamic count of rows based on the number of rows in a source table in MySQL database. In the application should be a checkbox in each row of the table. After clicking on the submitt button there should be update of records in the source table and it should be update just of these records where the checkboxes were checked.
The table in the application looks simillar like in the picture.
The primary key in the source table is in the column NUMBER. As a first try I simulated that after clicking on submitt button there will be shown the msgbox with the values from the column NUMBER for the rows, where the checkboxes were checked.
<html>
<head>
<title>APLICATIONa</title>
<script type="text/javascript">
function GetSelected() {
//Reference the Table.
var grid = document.getElementById("Table");
//Reference the CheckBoxes in Table.
var checkBoxes = grid.getElementsByTagName("INPUT");
var message = "\n";
//Loop through the CheckBoxes.
for (var i = 0; i < checkBoxes.length; i++) {
if (checkBoxes[i].checked) {
var row = checkBoxes[i].parentNode.parentNode;
message += " " + row.cells[1].innerHTML;
message += "\n";
}
}
//Display selected Row data in Alert Box.
alert(message);
}
</script>
</head>
<body>
<?php
$values = mysql_query("SELECT * FROM table_03_2020");
echo "<br><form action='main.php' method='POST'>";
echo "<input type='submit' name='button' value='Get Selected' class='btn btn-primary' onclick='GetSelected()' />";
echo "<table id = 'Table' border='0px' bordercolor='silver' cellpadding='1' cellspacing='2' width='100%'>";
echo "<tr bgcolor='#EEEEEE' height='45px'><th></th><th><b>NUMBER</b></th><th><b>NAME</b></th></tr>";
while ($zaznam=MySQL_Fetch_Array($values)):
echo "<tr onmouseover=\"highlight_row(this, 1, '#F2F2F2');\" onmouseout=\"highlight_row(this, 0, '#F2F2F2');\">";
echo "<td><input type='checkbox' name='cbox[]' ></td>";
echo "<td><font color='red'>".$zaznam["number"]."</font></td>";
echo "<td>".$zaznam["name"]."</td>";
echo "</tr>";
endwhile;
echo "</table><br>";
echo "</form>";
?>
</body>
</html>
The msgbox is just an illustration. Instead of msgbox, I need that after clicking on the submit button, there should be an update for these records in the source table, where the checkboxes were selected (so of these records, which are now shown in the msgbox). So I need something like:
"UPDATE table_03_2020 SET column1 = 'xy' where NUMBER in ('values of NUMBER from rows, where the checkbox was checked)"
There'll be also a second submit button and after clicking on it, there should be another different update. So after clicking on the second button, I need something like:
"UPDATE table_03_2020 SET column1 = 'ab' where NUMBER in ('values of NUMBER from rows, where the checkbox was checked)"
I'm sorry if my question is not so clear, but I'd really appreciate any help.
Thank you very much.
Add key values with the number to the cbox form variable:
echo "<td><input type='checkbox' name='cbox[" .$zaznam["number"]. "]' ></td>";
Then use the following PHP to get the number list.
if (isset($_POST["cbox"])) {
$checked = array();
foreach($_POST["cbox"] as $number => $val) {
$checked[] = addslashes($number);
}
$checked_list = implode(",", $checked);
}
The addslashes function is for SQL Injection protection.
This will create a list with comma separated numbers.
Than, you can insert it in the the SQL query.
UPDATE table_03_2020 SET column1 = 'xy' where NUMBER in ('. $checked_list .')
If you assign a value to the checkboxes, like this:
<input type='checkbox' name='cbox[]' value='{$zaznam["number"]}' >
When the form is submitted the cbox variable will contain an array of these numbers, which means that you can process them like this:
<?php
include 'db.php'; #your database connection!!!
$sql='update table_03_2020 set `column1`="XY" where `column2` in ( ? )';
$stmt=$db->prepare( $sql );
$ids=implode(',',$_POST['cbox']);
$stmt->bind_param('s',$ids);
$stmt->execute();
?>
Note that the above has not been tested so there might be errors but I hope it'll give the idea.
Thank you, I tried to improve the part of the code to:
echo "<input type='submit' name='buttonupdate' value='Get Selected' >";
echo "<table id = 'Table' border='0px' bordercolor='silver' cellpadding='1' cellspacing='2' width='100%'>";
echo "<tr bgcolor='#EEEEEE' height='45px'><th></th><th><b>NUMBER</b></th><th><b>NAME</b></th></tr>";
while ($zaznam=MySQL_Fetch_Array($values)):
echo "<tr onmouseover=\"highlight_row(this, 1, '#F2F2F2');\" onmouseout=\"highlight_row(this, 0, '#F2F2F2');\">";
if ($_POST["buttonupdate"]) {
if (isset($_POST["cbox"])) {
$checked = array();
foreach($_POST["cbox"] as $number => $val) {
$checked[] = addslashes($number);
}
$checked_list = implode(",", $checked);
}
}
echo "<td><input type='checkbox' name='cbox[" .$zaznam["cflot"]. "]' ></td>";
It didn't work, there was no update. Did I edited the code incorrectly?
Actually I forgot to mention the second button, so I edited my first post. Would it be possible to distinguish between the first and the second button? Thank you very much for any help.

Using a form to allow user to delete record from database

I am trying to echo a form through PHP so that the submit button value looks like a URL, which is does perfectly with this code. Next I am trying to get the WID value from a previous query with the variable $resulting[WID].
I know this variable is capturing the value correctly. The problem I am having is that I can't seem to get the form below to pass this value to my PDO query so that the record will be deleted from the database if the user clicks on "Delete". Can anyone see what I'm doing wrong?
//Get WID from form
if(isset($_POST['remove'])){
$the_WID = $_POST['WID'];
//The PDO query
$dlt = "DELETE FROM writing WHERE writing.WID = :writing.WID";
$stmtdlt = $dbh->prepare($dlt);
$stmtdlt->bindParam(':writing.WID', $the_WID, PDO::PARAM_INT);
$stmtdlt->execute();
}
//THE FORM (displayed so that it looks like a text link through PHP echo)
echo "<table class=\"edit\"><tr class=\"edit\"><td class=\"edit\"><FORM METHOD=\"POST\"
style=\"display: inline\" ACTION=\"\" class=\"ten\">";
echo "<input TYPE=\"submit\" name=\"remove\" VALUE=\"Delete\">";
echo "<input TYPE=\"hidden\" name=\"remove\" VALUE=\"$resulting[WID]\">";
echo "</FORM></td>";
echo "</tr></table>";

HTML form with checkbox and number types submission with PHP?

For learning purposes, I'm doing this website where user can select some items and the number of units he wants, let's say it's this simplest shopping app.
So, I read from database the existing items in catalog:
$queryResult=$mySQL->query("SELECT nombre, precio, id FROM productos");
Then I print the list of products:
$queryResult=$mySQL->query("SELECT nombre, precio, id_producto FROM productos");
echo "<form action=\"checkout.php\" method=\"POST\">";
while($datos=$mySQL->fetch_array($queryResult))
{
$nombre=$datos['nombre'];
$id_producto=$datos['id_producto'];
$precio=$datos['precio'];
echo "<h1>$nombre</h1>";
echo "<input type=\"checkbox\" name=\"$id_producto\" value=\"on\"> Cantidad: <input type=\"number\" name=\"$id_producto"."Number\""." min=\"1\" max=\"20\" step=\"1\" value=\"1\"><br>";
echo "<h3>Precio: $precio</h3><br>";
}
echo "<br>";
echo "<input type=\"submit\" class=\"button\" value=\"Comprar\">";
echo "</form>";
They get as value the ones from $id_producto, in the case of the number type inputs I concatenate "Number" so they dont get the same name.
After submission, I'm trying to do something like:
foreach($_POST as $post_key => $post_value){
if ($post_value=="on") {
$var1 = $_POST['.$post_key."Number".'];
}
}
So if a checkbox was selected I check for its corresponding numeric value.
Is it OK to perform another $_POST['somevariable'] inside that loop?
How can I concatenate that argument inside the square brackets?
You don't need the single quotes, that's for when the key is a constant string. Since your key is an expression, just put that expression inside the brackets:
if ($post_value=="on") {
$var1 = $_POST[$post_key."Number"];
}
A better way to do this is to post the inputs as arrays:
echo "<input type=\"checkbox\" name=\"producto[]\" value=\"$id_producto\"> Cantidad: <input type=\"number\" name=\"Number[$id_producto]\" min=\"1\" max=\"20\" step=\"1\" value=\"1\"><br>";
Then you can use the loop:
foreach ($_POST['producto'] as $post_value) {
$var1 = $_POST['Number'][$post_value];
}

Submit of selected on checkbox items?

I print this form in a web page with php:
<?php
include("connectDB.php");
$mySQL=new MySQL();
$queryResult=$mySQL->query("SELECT nombre, precio, id_producto FROM productos");
echo "<form action= 'checkout.php'> method=''POST'";
while($datos=$mySQL->fetch_array($queryResult))
{
$n = 1;
$nombre=$datos['nombre'];
$id_producto=$datos['id_producto'];
$precio=$datos['precio'];
echo "<h1>$nombre</h1>";
echo "<input type=\"checkbox\" name=\"$id_producto\" value=\"$nombre\"> Cantidad: <input type=\"number\" name=\"points\" min=\"1\" max=\"20\" step=\"1\" value=\"1\"><br>";
echo "<h3> Precio: $precio<br>";
}
echo "<br>";
echo "<input type=\"submit\" class=\"button\" value=\"Comprar\">";
echo "</form>";
?>
So it displays a list (which is a form within) of items which can be selected or checked, on submit, I want to do the $_POST[''] of only the checked items, how could I solve this?
When such checkboxes are printed, only those values which were checked are submitted.
If i understood you correctly you wanted to retrieve those that got posted, which you can follow with this simple method
foreach($_POST as $post_key => $post_value){
//Check that the particular input is int and numeric, since i believe the name is the id
if(is_numeric($post_key) && is_int($post_key){
//Here goes your code, $post_key is the id and $post_value is the $nombre
//Although i admit that i have no idea what nombre is since it is in another language. Forgive me if id_producto is not numeric and unique.
}
}

send id of all selected option from one page to another without $_post[]

<?php
$i=1;
$ph='php';
echo "<form method=\"post\" action=\"\">";
$query=mysql_query("select question,id from ques where category=\"$ph\" order by rand() limit 5",$con);
if(!$query)
{
echo mysql_error().'query failed';
}
$ans=1;
while($value1=mysql_fetch_array($query))
{
echo "Q-$i"." ";
echo $value1['question']."<br />";
$i++;
$qno=$value1['id'];
$query1=mysql_query("select id,option1,option2,option3,option4 from ques where id=$qno");
if(!$query1)
{
echo mysql_error().'query failed';
}
while($value2=mysql_fetch_array($query1))
{
$opt=$value2['option1'];
$opt1=$value2['option2'];
$opt2=$value2['option3'];
$opt3=$value2['option4'];
$id=$value2['id'];
echo "<input type=\"radio\" value=\"$opt\" name=\"$ans\">";
echo "<span class=\"margin\">$opt</h1>";
echo "<input type=\"radio\" value=\"$opt1\" name=\"$ans\">";
echo "<span class=\"margin1\">$opt1</h2>";
echo "<input type=\"radio\" value=\"$opt2\" name=\"$ans\">";
echo "<span class=\"margin2\">$opt2</h3>";
echo "<input type=\"radio\" value=\"$opt3\" name=\"$ans\">";
echo "<span class=\"margin3\">$opt3</h4>"."<br /><br />";
$ans++;
}
}
echo"<center>"."<input type=\"submit\" name=\"submit\" value=\"submit\">"."</center>";
echo "</form>";
if(isset($_POST['submit']))
{
$correct=$_POST[1];
$_SESSION['value']=$correct;
/*$correct1=$_SESSION['value'];
echo $correct1;*/
$correct2=$_POST[2];
$_SESSION['value1']=$correct2;
/*$correct3=$_SESSION['value1'];
echo $correct3;*/
$correct4=$_POST[3];
$_SESSION['value2']=$correct4;
/*$correct5=$_SESSION['value2'];
echo $correct5;*/
$correct6=$_POST[4];
$_SESSION['value3']=$correct6;
/*$correct7=$_SESSION['value3'];
echo $correct7;*/
$correct8=$_POST[5];
$_SESSION['value4']=$correct8;
/*$correct9=$_SESSION['value4'];
echo $correct9;
$j=1;
while($j<=$i-1)
{
$correct=$_POST[$j];
$_SESSION['$j']=$correct;
$j++;
$correct1=$_SESSION['$j'];
echo $correct1."<br />";
}*/
header("location:quizresult.php");
}
?>
I don't know how to send id of selected option to the next page.I want to retrieve the id of selected option in the next page because from this i can get the correct answer of the selected question or any other solution of this and i get the only one id on the next page
There are several ways how to carry over values to the next page. I used the following successfully before:
1. Use a $_SESSION variable
Save the option values in session variables and retrieve them on the next page.
2. Use hidden form fields
You can save them as part of the form but in a hidden form field and retrieve it on the next page via $_POST.
An excellent tutorial (4 pages) for HTML forms and its various inputs is here:
http://www.javascript-coder.com/html-form/html-form-tutorial-p1.phtml
3. Use a http query
You can append a http query to your link to the next page, containing the values, i.e.
http://www.example.com/next-page?option1=value1&option2=value2
On the next page you can use parse_url($url, PHP_URL_QUERY) to extract the values. I would recommend that only if you do not submit a form though. I use this option if I create action buttons that are linking to the next (or the same) page and a single action has to be performed before the page is displayed.
Some generic info about query strings: http://en.wikipedia.org/wiki/Query_string
$qno= $_SESSION['id'] = $value1['id'];
Id is being saved in $_SESSION['id'] and will be available on the ext page also.
retrieve it like this
$id = $_SESSION['id'];

Categories