PHP update SQL from multiple HTML checkbox - php

So, I need to make sure this sets the right parameters to the DB when pressing the buttons. I just want to get the calls and comparisons right so it does what it should when I hit the buttons. There should be one delete button for each row from database, and update page when I press it.
It should be possible to update the text/numbers in the forms presented by MySQL by changing the forms and press Save-button, then refresh the page.
$counter = 1;
if(isset($_POST['save']) and something is changed from the forms compared to DB) {
Update MySQL
Refresh page
<script>
window.location.replace("thispage.php");
</script>
}
if(isset($_POST['del'])) {
DELETE MySQL
Refresh page
<script>
window.location.replace("thispage.php");
</script>
}
echo "<tr><td>ID</td><td>Namn</td><td>Platser</td><td>Fullbokad</td><td>Ta bort</td></tr>";
$sqlListSections = "SELECT * FROM avdelningar WHERE user = {$_SESSION['id']}";
$queryListSections = mysqli_query($mysqli, $sqlListSections);
$del = [];
while($rowListSections = mysqli_fetch_array($queryListSections))
{
if($counter%2)
{
echo "\n<tr bgcolor=#F1F1F2>\n\n";
}else
{
echo "\n<tr bgcolor=#FFFFFF>\n\n";
}
$counter++;
echo "
<td>".$rowListSections['id']."</td>
<td>
<input type=text value=".$rowListSections['namn']."></td>
<td>
<input type=text value=".$rowListSections['platser']."></td>
<td>";
if($rowListSections['prio'] == 1)
{
echo "<select name=platser>
<option selected value=".$rowListSections['prio'].">".$rowListSections['prio']."</option>
<option value='0'>0</option>".$rowListSections['prio'];
}elseif($rowListSections['prio'] == 0)
{
echo "<select name=platser>
<option selected value=".$rowListSections['prio'].">".$rowListSections['prio']."</option>
<option value='1'>1</option>".$rowListSections['prio'];
}
echo "</td>
<td>
<form method=post action=thispage.php>
<input type=submit value=Delete name=del>";
</td>
</form>
</tr>";
}
echo "<form method=post action=thispage.php>
<input type=submit value=Save name=save>";
`

in your checkbox change naming as array.
<input type=checkbox name="del[]" value={$rowListSections['id']}>
like
echo $rowListSections["id"].' '.$rowListSections["namn"].' '.$rowListSections["platser"].' '.
$rowListSections["prio"].'';
and in your if(isset($_POST)) you can get a del array so you can loop this array like below.
foreach($del as $val){
$id = $val;
$sql_query_for_update = "update table_name set field = 1 where id= '$id' ";
}

Related

update existing row in mysql using php coding

in my db i have 20+ columns. i added 19 columns throught input form and stored in db succesfully. i fetch few rows from db in my main page. in my main page 1 more column is there. that is status column, it is a combo box type. if i click status column it should show 4 values. i want to select one of the values and then when i click save button it must go to stored in db with that same ID. how to do that? i tried but its not updated in mysql db...
mainpage combo box coding:
echo "\t<td><form action=statusdb.php method=post>
<select name=update><option value=empty></option><option value=Confirm>Confirm</option><option value=Processing>Processing</option><option value=Pending>Pending</option><option value=Cancelled>Cancelled</option></select>
<input name=\"update[".$a_row['slno']."]\"; type=submit id=id value=Save></form>
</td>\n";
status db coding:
if (isset($_GET['id']))
{
$id = mysql_real_escape_string($_GET['id']);
$sql = mysql_query("UPDATE guestdetails SET status = '" . $_POST['update'] ."'");
if(!$sql)
{
die("Error" .mysql_error());
}
}
help me how to do that?
In your IF should be $_POST, not $_GET
Also, need to add WHERE clause, like this:
if (isset($_POST['id']))
{
$id = mysql_real_escape_string($_POST['id']);
$update= mysql_real_escape_string($_POST['update']);
$sql = mysql_query("UPDATE guestdetails SET status = '$update' WHERE id='$id'");
if(!$sql)
{
die("Error" .mysql_error());
}
}
Also, you used name update twice, once in <select> once in <input>, take that one from <input> out, make it hidden field with name id and value of your slno row:
echo "\t<td>
<form action=statusdb.php method=post>
<select name=update>
<option value=empty></option>
<option value=Confirm>Confirm</option>
<option value=Processing>Processing</option>
<option value=Pending>Pending</option>
<option value=Cancelled>Cancelled</option>
</select>
<input name='id' type='hidden' value='".$a_row['slno']."';>
<input type='submit'>Save</button>
</form>
</td>\n";
Try like below:
<form action="statusdb.php" method="post">
<?php
while($a_row = mysql_fetch_array($sql)) {
$sl_no = $a_row['slno'];
echo '<select name="update['.$sl_no.']"><option value=empty></option><option value=Confirm>Confirm</option><option value=Processing>Processing</option><option value=Pending>Pending</option><option value=Cancelled>Cancelled</option></select> ';
echo '<input type="hidden" name="sl_no[]" value="'.$sl_no.'" />';
}
?>
<input name="update_rows" type="submit" value="Save">
</form>
<?php
if(isset($_POST['update_rows'])) {
$nums = $_POST['sl_no'];
$update = $_POST['update'];
foreach($nums as $sl) {
$sl_no = $sl;
$val = $update[$sl_no];
$sql_update = mysql_query("UPDATE guestdetails SET status = '$val' WHERE sl_no='$sl_no'");
}
}
?>
you are not submitting any id to status db.

If uncheck the check box delete row in my SQL table

Actually I am very new to php.. I have a task that select records from database as checkboxes checked. When I uncheck a checkbox it should delete that particular record from my database..
My code is
<?php
if(isset($_POST['delete']))
{
$test=$_POST['test'];
$qun1=$_POST['question1'];
//DB connection
$CON=mysql_connect("localhost","root","");
mysql_select_db("Dbname");
if($qun1!=0 && $test!=0)
{
foreach($qun1 as $qunestion)
{
echo $question; //this is for testing
$query=mysql_query("delete from test_question where test_questions_id='$test' AND question_id IN ('$question') " ) or die(mysql_error());
}
if($query)
{
echo "success";
}
else
{
echo "No";
}
}
}
?>
my code is working properly but if i use NOT IN in the place of IN it is not working..why?..if unchecked the records it should be delete..i already retrieve records from database as checked fields..
My html markup:
<script>
function fun2(ts)
{
$.post("ajax2.php",{qs:ts},function(data)
{
document.getElementById('div1').innerHTML=data
})
}
</script>
<form action="somepage.php" method="post">
//dynamic selection test code
<select name="test" id="test" onChange="fun2(this.value);">
<option value="">Select Test</option> </select>
<div id="div1" > </div>
<input type="submit" name="delete" value="Delete" >
</from>
my ajax code:
<?php
$qs=$_REQUEST['qs'];
mysql_connect("localhost","root","");
mysql_select_db("advancedge");
$sql=mysql_query("select question_id from test_question where test_questions_id='$qs'");
if($sql)
{
while($rec=mysql_fetch_row($sql))
{
echo "<input type='checkbox' name='question1[]' value='$rec[0]' checked='checked' >";
}
}
?>
If I understand correctly, you want to delete as soon as the item is unchecked? To check if a checkbox is unchecked, you have to use javascript. PHP runs on the server, not the client side (you could use ajax, but I would recommend not to for this).
I would recommend, you delete whatever you want to on form submission, if you don't know how to do that,I can tell you if you post the html part up.
I would also recommend you learn PHP from a course on the internet, so you know some standards and get some good practices. (Youtube or Lynda.com)
It is an old post, but if someone end up here - this might solve the problem:
<?php
echo "<form action='' method='post'>";
echo "<input type='checkbox' id='chk_1' name='chk_1' value='First' />chk 1 </br>";
echo "<input type='checkbox' id='chk_2' name='chk_2' value='Second' />chk 2 </br>";
echo "<input type='submit' />";
echo "</form>";
$check = array();
// Set all checkboxes to 0 if unchecked
for($i = 1; $i<=2; $i++) {
$check["chk_$i"] = isset($_POST["chk_$i"]) ? 1 : 0;
}
// Output of the array
echo '<pre>';
var_export($check);
echo '</pre>';
The code will set all unchecked checkboxes to 0.
Then you have to take care of that using something like this:
<?php
if($_GET['chk_1'] == 0) {
$sql = "DELETE FROM mytable WHERE...";
}

displaying results based on combobox selection

I have a dynamic combobox and I have my Fetch button. When a user selects a value from combobox and clicks fetch button, all the other related values are displayed in a textbox for the user to edit and update records. And that works fine.
<form id="form1" method="post" action="edit.php">
<select name="ID" id="select">
<?php display_Id();?>
</select>
<input type="submit" name="Fetch" id="Fetch" value="Fetch" />
</form>
function display_Id() {
$query = "SELECT * FROM Flight";
$result = mysql_query($query) or die("Failed to fetch records");
confirm_query($result);
while($rows = mysql_fetch_array($result)) {
$flightNum = $rows['FlightNo'];
echo "<option value=\"$flightNum\" ";
echo " selected";
echo "> $flightNum </option>";
}
}
The problem is in the Fetch button. When user clicks Fetch, other values are displaying but the selected value from combobox is refreshing. How to make the values remain selected even after pressing the Fetch button?
Your question is incomplete in the sense, that you don't have your dislay_Id() code shown here. However, Generally speaking, you should add selected after <option value="something" programmatically,
Code should be something like this:
function displayId(){
if($value[x]== $currentValue) {
echo "<option value='$value[x]' selected>sth</option>";
}
else
{
echo "<option value='$value[x]'>sth</option>";
}
}
EDIT:: Your code adds a "selected" to each of the values, you must only add a "selected" to a current value.
So, your code must look like this:
echo "<option value=\"$flightNum\" ";
if($_POST['ID'] == $flightNum)
{
echo " selected";
}
echo "> $flightNum </option>";
while($rows = mysql_fetch_array($result))
{
$flightNum = $rows['FlightNo'];
echo "<option value=\"$flightNum\" ";
if($_POST['ID'] == $flightNum)
{
echo " selected";
}
echo "> $flightNum </option>";
}

php checkbox from mysql

I've managed to pull records from a mysql database using php with a checkbox to select. I'm struggling to make the selected records (with the checkboxes) appear on a new page. Here is my code so far:
<?php
include('connect.php');
$query = 'SELECT * FROM grades';
if ($r = mysql_query($query)) {
print "<form>
<table>";
while ($row = mysql_fetch_array($r)) {
print
"<tr>
<td>{$row['InstitutionName']}</td>
<td>{$row['InstitutionAddress']}</td>
<td>{$row['SubjectArea']}</td>
<td><input type='checkbox' name='check[$row{['GradeID']}] value='check' /></td>
</tr>";
}
print "</table>
</form>";
$checkbox[] = isset($_POST['checkbox']) ? true : false;
} else {
print '<p style="color: blue">Error!</p>';
}
?>
<html>
<form action="check2.php" method="POST">
<input type='submit' name='Submit' value='Submit'>
</html>
And on the page where I want the selected records to display, I have:
<?php
if(isset($checkbox))
{
foreach($checkbox as $value)
{
echo $value."<br>"; //it will print the value of your checkbox that you checked
}
}
?>
Any assistance would be appreciated!
Put checked="checked" just like you have put value="check":
<td><input type='checkbox' name='check[$row{['GradeID']}] value='check' checked="checked" /></td>
Edit:
Probably I misunderstood you. What do you expect to see?
First, you should make the form to perform POST request instead of GET (default):
print "<form method='POST' action='THE_FILE_YOU_PRINT_RESULTS.php'>"
Then in "THE_FILE_YOU_PRINT_RESULTS.php" do a print_r($_POST); to see what you get and how to display it.
A better way to do this would be to name your checkboxes check[]. Each checkbox value should then be the ID (rather than check).
Then on your results page, just loop through each instance of check[] and print the value out.
check[$row{['GradeID']}]
Seems incorrect to me, should it be:
check[{$row['GradeID']}]
Notice the moved opening curly bracket to before the $
Sorry if this is wrong haven't used PHP in long time but it stood out for me
The are a couple of error in the form print function.
You have to put the action on the first form, not on the second, you have to change the way how you print the checkbox as well.
Try to print the form in this way:
<?php
include('connect.php');
$query = 'SELECT * FROM grades';
if ($r = mysql_query($query)) {
print "
<form action=\"check2.php\" method=\"POST\">
<table>";
while ($row = mysql_fetch_array($r)) {
print
"<tr>
<td>{$row['InstitutionName']}</td>
<td>{$row['InstitutionAddress']}</td>
<td>{$row['SubjectArea']}</td>
<td><input type='checkbox' name='check[".$row['GradeID']."] value='".$row['GradeID']."' /></td>
</tr>";
}
print "</table>
<input type='submit' name='Submit' value='Submit'>
</form>";
$checkbox[] = isset($_POST['checkbox']) ? true : false;
} else {
print '<p style="color: blue">Error!</p>';
}
?>
And print the checked box reading the _REQUEST array:
<?php
if(isset($_REQUEST["check"]))
{
foreach($_REQUEST["check"] as $key=>$value)
{
echo $key."<br>"; //it will print the value of your checkbox that you checked
}
}
?>
This should work.

how do you use multiple dropdowns and know which status each has?

the below code shows a table with users to be accepted or declined. the code as it is has a dropdown on the end allowing to either accept it, deny it or leave as is. there is a button on the bottom to submit the form and after that there should be a php script that decides which user is accepted, denied or still pending.
what would be the best approach to make this work since i find it hard to link the dropdown box and the id.
<table align='center' width='90%'>
<tr>
<center><td><strong>ID:</strong></td></center>
<center><td><strong>Name:</strong></td></center>
<center><td><strong>Level:</strong></td></center>
<center><td><strong>Job:</strong></td></center>
<center><td><strong>Guild:</strong></td></center>
<center><td><strong>Date:</strong></td></center>
<center><td><strong>Action:</strong></td></center>
</tr>
<?php
$id = 0;
$result=mysql_query("SELECT * FROM accounts WHERE active ='0' ORDER BY date LIMIT 10") or die(mysql_error());
while($row = mysql_fetch_array( $result )) {
$id = $id + 1;
?>
<form method='POST' action=''>
<tr>
<center><td><?php echo $row['id']; ?></td></center>
<center><td><?php echo $row['user']; ?></td></center>
<center><td><?php echo $row['level']; ?></td></center>
<center><td><?php echo $row['job']; ?></td></center>
<center><td><?php echo $row['guild']; ?></td></center>
<center><td><?php echo $row['date']; ?></td></center>
<td>
<select name='action_<?php echo $row['id']; ?>'>
<option value='none'>None</option>
<option value='accept'>Accept</option>
<option value='decline'>Decline</option>
</select>
</td>
</tr>
<?php } ?>
<tr>
<br /><td align='right'><input type='submit' value='Submit' name='submit' /></td>
</tr>
</form>
</table>
<?php
if(isset($_POST['submit'])) {
if(isset($_POST['action_'.$row['id'].'']) && $_POST['action_'.$row['id'].''] == "accept" ) {
$acc = mysql_query("UPDATE `accounts` SET `active`='1' WHERE `id` = '".$row['id']."'");
echo "<meta http-equiv=refresh content=\"5; url=?wesofly=main&page=recruitment\">";
}elseif(isset($_POST['action_'.$row['id'].'']) && $_POST['action_'.$row['id'].''] == "decline" ) {
$dec = mysql_query("DELETE * from `accounts` WHERE '".$row['id']."'");
echo "<meta http-equiv=refresh content=\"0; url=?wesofly=main&page=recruitment\">";
}
}
?>
Your code is confusing. Your WHILE loop starts before the form tag, but the WHILE loop closes before the form tag closes. This means that you are going to have multiple form elements.
So, first of all, change that in your code. Next the way you want this to work is using arrays.
Your drop down box should look like this
<select name='action[<?php echo $row['id']; ?>]'>
<option value='none'>None</option>
<option value='accept'>Accept</option>
<option value='decline'>Decline</option>
</select>
Then on the PHP side, you should be able to do something like
foreach ($_REQUEST['action'] as $key => $value) {
$id = $key;
$status = $value;
// put your code here to update the specific database item
}
I think you'll be better off with HTML form arrays, for instance:
<select name="action[<?php echo $row['id']; ?>]">
<option value="none">None</option>
<option value="accept">Accept</option>
<option value="decline">Decline</option>
</select>
And inside your php code, you would simply loop through the submitted action field in your $_POST array to find which id had which action. Each entry would be presented as an array, the key would be the user's id.

Categories