keep data in form when clicking submit - php

EDIT: Apologies - all code now pasted below
Apologies for the first time newbie question - I've been looking for an answer here and on google - I get the feeling this is some simple coding i'm messing up.
I've created a form which, when you validate, you check all the data on the same page and the original data is kept in the original form so you can make changes if you wish.
I have a section of the form where this doesn't work however - where you can ask multiple questions and each question can have up to 4 answers.
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<head>
<title>Test page</title>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<link rel="stylesheet" href="stylenewtest.css" type="text/css" />
<script language="javascript" src="tableadd.js"></script>
</head>
<body>
<?php
$string = isset($_POST['quiz_format']) ? $_POST['quiz_format'] : false;
$quiz_format = ereg_replace("[^0-9a-zA-Z?ąćęłńóśżźĄĆĘŁŃÓŚŻŹ\. ]", "", $string);
$stringquiz_100 = isset($_POST['quiz_100']) ? $_POST['quiz_100'] : false;
$quiz_100 = ereg_replace("[^0-9a-zA-Z?ąćęłńóśżźĄĆĘŁŃÓŚŻŹ\. ]", "", $stringquiz_100);
$stringquiz_fback = isset($_POST['quiz_fback']) ? $_POST['quiz_fback'] : false;
$quiz_fback = ereg_replace("[^0-9a-zA-Z?ąćęłńóśżźĄĆĘŁŃÓŚŻŹ\. ]", "", $stringquiz_fback);
$stringquiz_title = isset($_POST['quiz_title']) ? $_POST['quiz_title'] : false;
$quiz_title = ereg_replace("[^0-9a-zA-Z?ąćęłńóśżźĄĆĘŁŃÓŚŻŹ\. ]", "", $stringquiz_title);
$stringquiz_instruct = isset($_POST['quiz_instruct']) ? $_POST['quiz_instruct'] : false;
$quiz_instruct = ereg_replace("[^0-9a-zA-Z?ąćęłńóśżźĄĆĘŁŃÓŚŻŹ\?,\"\'\._#\\/ !&()=\+;:\t\r\n-]", "", $stringquiz_instruct);
$stringquiz_time = isset($_POST['quiz_time']) ? $_POST['quiz_time'] : false;
$quiz_time = ereg_replace("[^0-9a-zA-Z?ąćęłńóśżźĄĆĘŁŃÓŚŻŹ\. ]", "", $stringquiz_time);
?>
<div id="content">
<p><span class="error">* required field.</span></p>
<form method="post" action="">
<div class="datagrid">
<table>
<tr><th colspan="2">Please choose the format of the quiz<span class="error">*</span></th></tr>
<tr><td>Hangman</td><td><input type="radio" name="quiz_format" <?php if (isset($quiz_format) && $quiz_format=="Hangman") echo "checked";?> value="Hangman"></td></tr>
<tr><td>Gap fill</td><td><input type="radio" name="quiz_format" <?php if (isset($quiz_format) && $quiz_format=="Gap fill") echo "checked";?> value="Gap fill"></td></tr>
<tr><td>Multiple choice</td><td><input type="radio" name="quiz_format" <?php if (isset($quiz_format) && $quiz_format=="Multiple Choice") echo "checked";?> value="Multiple choice"></td></tr>
<tr><td>Simple Q & A</td><td><input type="radio" name="quiz_format" <?php if (isset($quiz_format) && $quiz_format=="Simple Q & A") echo "checked";?> value="Simple Q & A"></td></tr>
<tr><td>Word formation hangman</td><td><input type="radio" name="quiz_format" <?php if (isset($quiz_format) && $quiz_format=="Word formation hangman") echo "checked";?> value="Word formation hangman"></td></tr>
</table>
</div>
<br />
<div class="datagrid">
<table>
<tr><th colspan="2">Continue repeating the exercise until 100% achieved?<span class="error">*</span></th></tr>
<tr><td>Yes</td><td><input type="radio" name="quiz_100" <?php if (isset($quiz_100) && $quiz_100=="Yes") echo "checked";?> value="Yes"></td></tr>
<tr><td>No</td><td><input type="radio" name="quiz_100" <?php if (isset($quiz_100) && $quiz_100=="No") echo "checked";?> value="No"></td></tr>
</table>
</div>
<br />
<div class="datagrid">
<table>
<tr><th colspan="2">Show the answer as correct/incorrect after every question or just at the end?<span class="error">*</span></th></tr>
<tr><td>After every question</td><td><input type="radio" name="quiz_fback" <?php if (isset($quiz_fback) && $quiz_fback=="After every question") echo "checked";?> value="After every question"></td></tr>
<tr><td>Just at the end</td><td><input type="radio" name="quiz_fback" <?php if (isset($quiz_fback) && $quiz_fback=="Just at the end") echo "checked";?> value="Just at the end"></td></tr>
</table>
</div>
<br />
<div class="datagrid">
<table>
<tr><th colspan="2">Please enter in the title of the quiz<span class="error">*</span></th></tr>
<tr><td>Quiz title:</td><td><input type="text" name="quiz_title" value="<?php echo $_POST[quiz_title];?>"></td></tr>
</table>
<br />
<table>
<tr><th colspan="2">Please enter in the instructions for the quiz<span class="error">*</span></th></tr>
<tr><td>Quiz instructions:</td><td><textarea name="quiz_instruct" rows="10" cols="40"><?php echo $_POST[quiz_instruct];?></textarea></td></tr>
</table>
</div>
<br />
<div class="datagrid">
<script language="javascript">
window.onload = moreFields;
window.onload = init;
</script>
<table>
<tr><th colspan="5">Please enter in the quiz's questions and answers:<span class="error">*</span></th></tr>
</table>
<div id="readroot" style="display: none">
<input type="button" value="Remove a question field"
onclick="this.parentNode.parentNode.removeChild(this.parentNode);" />
<table>
<tr>
<td>Question:</td>
<td colspan="3"><input type="text" name="q[]" value="<?php echo $_POST['q'][$i] ?>"></td>
</tr>
<tr>
<td>Answer 1:</td>
<td>Answer 2:</td>
<td>Answer 3:</td>
<td>Answer 4:</td>
</tr>
<tr>
<td><input type="text" name="a1[]" value="<?php echo $_POST['a1'][$i] ?>"></td>
<td><input type="text" name="a2[]" value="<?php echo $_POST['a2'][$i] ?>"></td>
<td><input type="text" name="a3[]" value="<?php echo $_POST['a3'][$i] ?>"></td>
<td><input type="text" name="a4[]" value="<?php echo $_POST['a4'][$i] ?>"></td>
</tr>
</table>
</div>
<span id="writeroot"></span><input type="button" id="moreFields" value="Click here to add further question fields" /><br />
</div>
<br />
<div class="datagrid">
<table>
<tr><td><input type="submit" name="Submit1" value="Submit"/></td></tr>
</table>
</div>
</form>
<?php
if ( isset( $_POST['Submit1'] ) ) {
echo "<form method=post action=insert.php>";
echo "<h1>Please confirm the quiz details are correct</h1>";
echo "<div class=datagrid>";
echo "<table>";
if(empty($string)){
echo("<tr><td>Quiz format:</td><td><h3>Please go back and choose a quiz format<h3></td></tr>");
$showbutton=1;
}
else{
echo("<tr><td>Quiz format:</td><td>" . $quiz_format . "</td></tr>");
echo("<input type=hidden name=quiz_format value='" . $quiz_format . "' />");
}
if(empty($stringquiz_100)){
echo("<tr><td>Continue repeating the exercise until a 100% score is achieved?:</td><td><h3>Please go back and choose an option<h3></td></tr>");
$showbutton=1;
}
else{
echo("<tr><td>Continue repeating the exercise until a 100% score is achieved?:</td><td>" . $quiz_100 . "</td></tr>");
echo("<input type=hidden name=quiz_100 value='" . $quiz_100 . "' />");
}
if(empty($stringquiz_100)){
echo("<tr><td>Do you want the answer to be shown after every question or at the end of the quiz?:</td><td><h3>Please go back and choose an option<h3></td></tr>");
$showbutton=1;
}
else{
echo("<tr><td>Do you want the answer to be shown after every question or at the end of the quiz?:</td><td>" . $quiz_fback . "</td></tr>");
echo("<input type=hidden name=quiz_fback value='" . $quiz_fback . "' />");
}
echo "</table>";
echo "</div>";
echo "<br />";
echo "<div class=datagrid>";
echo "<table>";
if(empty($stringquiz_title)){
echo("<tr><td>Quiz title:</td><td><h3>Please go back and enter in a title for the quiz</h3></td></tr>");
$showbutton=1;
}
else{
echo("<tr><td>Quiz title:</td><td>" . $quiz_title . "</td></tr>");
echo("<input type=hidden name=quiz_title value='" . $quiz_title . "' />");
}
if(empty($stringquiz_instruct)){
echo("<tr><td>Quiz instructions:</td><td><h3>Please go back and enter in instructions for the quiz</h3></td></tr>");
$showbutton=1;
}
else{
echo("<tr><td>Quiz instructions:</td><td>" . $quiz_instruct . "</td></tr>");
echo("<input type=hidden name=quiz_instruct value='" . $quiz_instruct . "' />");
}
echo "</table>";
echo "</div>";
echo "<br />";
echo "<div class=datagrid>";
echo "<table>";
if(empty($stringquiz_time)){
echo("<tr><td>Time limit:</td><td>not specified</td></tr>");
}
else
{
echo("<tr><td>Time limit:</td><td>" . $quiz_time . "</td></tr>");
echo("<input type=hidden name=quiz_time value='" . $quiz_time . "' />");
}
echo "</table>";
echo "</div>";
echo "<br />";
echo "<div class=datagrid>";
echo "<table>";
echo "<tr><td colspan=5>The questions and answers to your quiz:</td></tr>";
$aq = $_POST['q'];
$aa1 = $_POST['a1'];
$aa2 = $_POST['a2'];
$aa3 = $_POST['a3'];
$aa4 = $_POST['a4'];
$N = count($aq);
for($i=1; $i < $N; $i++){
if($aq[$i]==""){
echo("<tr><td>Question:</td><td><h3>Please go back and enter a question</h3></td></tr>");
$showbutton=1;
}
elseif($aa1[$i]==""){
echo("<tr><td>Answer:</td><td><h3>Please go back and enter at least one answer</h3></td></tr>");
$showbutton=1;
}
else{
echo ("<table><tr><td>Question:</td><td colspan=3>" . $aq[$i]. "<input type=hidden name=q[] value='" . $aq[$i] . "'></td></tr>
<tr><td>Answer 1:</td><td>Answer 2:</td><td>Answer 3:</td><td>Answer 4:</td></tr>
<tr><td>" .$aa1[$i] . " <input type=hidden name=a1[] value='" .$aa1[$i] . "'></td>
<td>" .$aa2[$i] . " <input type=hidden name=a2[] value='" .$aa2[$i] . "'></td>
<td>" .$aa3[$i] . " <input type=hidden name=a3[] value='" .$aa3[$i] . "'></td>
<td>" .$aa4[$i] . " <input type=hidden name=a4[] value='" .$aa4[$i] . "'></td> </tr></table>");
}
}
echo "</table>";
echo "</div>";
echo "<br />";
echo "<div class=datagrid>";
echo "<table>";
echo "<tr><td><input type=button value='<< Go Back' onclick='goBack()' /></td></tr>";
if ($showbutton =="1"){
}
else{
echo "<tr><td><input type=submit value=Submit></td></tr>";
echo "</table>";
echo "</form>";
}
}
?>
</div>
</body>
</html>
but every time I submit, the questions and answers carry through but the form fields lose all the data. How can I keep the data in the fields?
Many thanks in advance

You can simply set the value of the input to either $_POST['old_value_name] or $_GET['old_value_name'] depending on which form method you are using. Therefore, your new code would look something like this (assuming that you are looking for the key $i from your question):
<table>
<tr>
<td>Question:</td>
<td colspan="3"><input type="text" name="q[]" value="<?php echo $_POST['q'][$i] ?>"></td>
</tr>
<tr>
<td>Answer 1:</td>
<td>Answer 2:</td>
<td>Answer 3:</td>
<td>Answer 4:</td>
</tr>
<tr>
<td><input type="text" name="a1[]" value="<?php echo $_POST['a1'][$i] ?>"></td>
<td><input type="text" name="a2[]" value="<?php echo $_POST['a2'][$i] ?>"></td>
<td><input type="text" name="a3[]" value="<?php echo $_POST['a3'][$i] ?>"></td>
<td><input type="text" name="a4[]" value="<?php echo $_POST['a3'][$i] ?>"></td>
</tr>
</table>

As far as I've understood your problem you want to keep values in a form after they were sent to server. "I've created a form which, when you validate, you check all the data on the same page and the original data is kept in the original form so you can make changes if you wish"
It's ok. I remember I wanted the same a few months ago. This is why I tried to help.
There is only a problem that after pressing "submit" button form is sent to server and page is reloaded.
In return you get a new page from webserver which you pointed in the form field "action".
I would do it so:
Target form: <br/>
<form id="target" action="index.php" method='post'>
<input name="first_field" type="text" value="<?php if ( isset($_POST['first_field']) )
echo $_POST['first_field']; ?>" /> <br/>
<input name="second_field" type="text" value="<?php if ( isset($_POST['second_field']))
echo $_POST['second_field'];?>" /> <br/>
<p><b>What kind of girls do you like?:</b><Br>
<input type="radio" name="browser" value="brunette" <?php if( $_POST['browser']==="brunette" ) echo "checked"; ?> > brunette<Br>
<input type="radio" name="browser" value="blonde" <?php if( $_POST['browser']==="blonde" ) echo "checked"; ?> > blonde<Br>
<input type="radio" name="browser" value="red" <?php if( $_POST['browser']==="red" ) echo "checked"; ?> > red<Br>
</p>
<input type="submit" />
</form>
Any ideas how it can be changed/improved are encouraged.

Related

passing while loop value to another form

In the code bellow, I'm able to fetch values from the database. Now the retrieved values need to be passed to another form.
PHP:
<?php
require('administrator/connect-db.php');
$www_root = 'http://localhost/secure/cem/administrator/profile/';
$qry = mysql_query("SELECT * from dealer_package_details");
if(!$qry){echo mysql_error();}else{
while($row = mysql_fetch_array($qry)){
echo "<div class='col-sm-4 sm-margin-b-50'>";
echo "<form action='test.php'>";
echo "<div class='margin-b-20'>";
echo "<div class='wow zoomIn' data-wow-duration='.3' data-wow-delay='.1s'>";
echo '<img class="img-responsive" name="pport" src="', $www_root, '/', $row['pport'], '" alt="', $row['pport'], '"/>';
echo "</div>";
echo "</div>";
echo "<h3><a href='#' name='name_of_the_product'>" . $row['package_id'].$row['name_of_the_product']."</a></h3>";
echo "<input type='submit' name='submit' value='book now'>";
echo "</div>";
}
}
?>
The following code describes the second form where the values need to be passed.
HTML:
<form method="POST" action="insrt.php">
<input name="name_of_the_product" type="text" class="form-control name_of_the_product" value="<?php echo $_POST["name_of_the_product"]; ?>" readonly/>
<input name="package_id" type="text" class="form-control package_id" value="<?php echo $_POST["package_id"]; ?>" readonly/>
<input type="submit" name="submit" value="Save">
I suggest to use input hidden.
PHP:
...
echo "<input type='hidden' name='description' value='".$row['description]."' />";
...
HTML:
...
<input name="description" type="text" value="<?php echo $_POST['description']; ?>">
...

storing value from radio button to database with looping

I am trying now to get the value of every radio button to store in a database.
The trick is I'm using while loop to display the question and the choices.
Here is my code in displaying the questions and choices.
class questions{
function __construct(){
$db= new dbConnect();
}
public function fetchRandom()
{
$qr=mysql_query("SELECT * FROM questionaires INNER JOIN choices ON questionaires.q_id=choices.q_id WHERE RAND()<(SELECT ((10/COUNT(*))*10) FROM questionaires) ORDER BY RAND() LIMIT 10");
$c=0;
echo "<table border='3' align='center' bordercolor='#CCCCCC'>
<tr>
<th>Number:</th>
<th>Question</th>
</tr>";
while($row=mysql_fetch_array($qr))
{
$c++;
echo "<tr>";
echo "<td>" . $c . "</td>";
echo "<td>";
echo $row['question'] . "<br>";
$ans_arr=array($row['choice_a'],$row['choice_b'],$row['choice_c'],$row['choice_d']);
shuffle($ans_arr);
echo "<input type='radio' name='ans".$c."' value='".$ans_arr[0]."'>".$ans_arr[0]."</input><br>";
echo "<input type='radio' name='ans".$c."' value='".$ans_arr[1]."'>".$ans_arr[1]."</input><br>";
echo "<input type='radio' name='ans".$c."' value='".$ans_arr[2]."'>".$ans_arr[2]."</input><br>";
echo "<input type='radio' name='ans".$c."' value='".$ans_arr[3]."'>".$ans_arr[3]."</input><br>";
echo "</td>";
echo "</tr>";
}
echo "</table>";
}
}
How can I store the answer of the user to database. Little help will be appreciated. Because I don't know how to code it from scratch. Thank you.
This is simple code try to code something like this.
<!DOCTYPE html>
<html>
<body>
<form method="post" action="">
<table>
<tr>
<td>Question 1</td>
<td><input type="radio" name="ques[ques1][ans1]" value="ans1" checked> Ans1
<input type="radio" name="ques[ques1][ans1]" value="ans2"> Ans2
<input type="radio" name="ques[ques1][ans1]" value="ans3"> Ans3
<input type="radio" name="ques[ques1][ans1]" value="ans4"> Ans4
</td>
</tr>
<tr>
<td>Question 1</td>
<td><input type="radio" name="ques[ques2][ans2]" value="ans1" checked> Ans1
<input type="radio" name="ques[ques2][ans2]" value="ans2"> Ans2
<input type="radio" name="ques[ques2][ans2]" value="ans3"> Ans3
<input type="radio" name="ques[ques2][ans2]" value="ans4"> Ans4
</td>
</table>
<input type="submit" name="submit" value="submit" />
</form>
</body>
</html>
<?php
if (isset($_POST['submit'])) {
$data = $_POST['ques'];
foreach ($data as $key => $ans) {
echo 'Question :'. $key .' '. 'Answer :'. array_values($ans)[0].'<br/>';
}
}
Hope this will help you :).

A form (action) error

I have a question, I have a page and a form that I direct it to itself to edit data to database.
I need a way to use the form and redirect itself with action=editcinemas.php?cinema_id=THE ID OF CINEMA
<html>
<body>
<form name="form3" method="post" action="editcinemas.php"> //MY PROBLEM IS HERE I GUESS
<td>
<table>
<?php
require('../classes/cinema_class.php');
$cinema=new cinema($_GET["cinema_id"]);
$cinemas = $cinema->get_all_cinemas();
foreach ($cinemas as $movie)
{
$cinema_id = $movie['cinema_id'];
$cinema_name = $movie['cinema_name'];
$cinema_location = $movie['cinema_location'];
}
echo "<input name='cinemaid' type='hidden' id='cinemaid' value=" . $cinema_id . '><br/>';
echo "Cinema Name :";
echo "<input name='cinemaname' type='text' id='cinemaname' value=" . $cinema_name . '><br/>';
echo "Cinema Location :";
echo "<input name='cinemalocation' type='text' id='cinemalocation' value=" . $cinema_location . '><br/>';
?>
</table>
<input type="submit" name="Edit" value="Edit"> <input type="reset" name="Reset" value="Reset"/><INPUT Type="button" VALUE="Back" onClick="history.go(-1);return true;">
</form>
</body></html>
<?php
$cinemaid=$_POST['cinemaid'];
$cinemaname=$_POST['cinemaname'];
$cinemalocation=$_POST['cinemalocation'];
if ($_POST) {
if(empty($cinemaname)){
echo "Cinema Name is a must"; }
else{
$update_movie=mysql_query("UPDATE `memoire`.`cinema`
SET `cinema_name`= '$cinemaname', `cinema_location`= '$cinemalocation'
WHERE `cinema_id`='$cinemaid'");
if($update_movie)
{ header("Refresh: 0;url=../listallcinemas.php");}
else
{ echo "error in registration".mysql_error(); }
}
?>
Just simply append it, like this:
<form name="form3" method="post" action="editcinemas.php?cinema_id=<?php echo $_GET["cinema_id"]; ?>">

need to delete selected rows through checkbox with a single Delete button

okay this is the updated main php page now, ive cleared my previous post to make this clean, FYI...what im posting here are just my test page which is he exact replica of my actual page..just have different php page name...
<link href="jquery-ui-1.10.2.custom/css/dark-hive/jquery-ui-1.10.2.custom.css" rel="stylesheet" type="text/css" />
<script type="text/javascript" src="jquery-ui-1.10.2.custom/js/jquery-1.9.1.js" ></script>
<script type="text/javascript" src="jquery-ui-1.10.2.custom/js/jquery-ui-1.10.2.custom.js" ></script>
<script type="text/javascript" src="jquery-ui-1.10.2.custom/js/jquery-ui-1.10.2.custom.min.js" ></script>
<link rel="stylesheet" href="style.css" />
<script type="text/javascript" src="SMP1_deletefromDB.js"></script>
<script>
$(document).ready(function(){
$("#results").show();
});
</script>
<script type="text/javascript">
$(document).ready(function(){
$("#RetrieveList").on('click',function() {
var xid = $('#XiD').val();
var date = $('#Date').val();
$.post('resultgenerator_test.php',{xid:xid, date:date}, function(data){
$("#results").html(data);
});
return false;
});
});
//post to delete.php file. In delete.php you can get the id's in $_POST['id'] as multidimensional array. You can handle the delete operation based on that
$(document).ready(function(){
$("#DeletefromDB").on('click',function() {
//get all the checked values from checkboxes
var ids = $('input[name=checkbox]:checked').map(function () {
return this.value;
}).get();
if (ids.length === 0)
return false; //show some error message
//post to delete.php file. In delete.php you can get the id's in $_POST['id'] as multidimensional array. You can handle the delete operation based on that
$.post('deletedata.php',{id : ids}, function(data){
$("#results").html(data);
//handle the message based on success or error
});
return false;
});
});
</script>
</head>
<body class="oneColFixCtrHdr">
<div id="container" style="width:auto">
<div id="header" style="background-color:#7BD12E">
<h1 align="left" style="color:#FFF; font-family: Arial, Helvetica, sans-serif;">PIS Ticket Tracking System</h1>
<!-- end #header --></div>
<div id="mainContent">
<h1 style="font-size:9"></h1>
<form id="form1" name="form1" method="post" action="">
<p>
<label for="Back"></label>
<input type="button" name="Back" id="Back" value="Back To Main" href="#" onclick="return backAway();" />
</p>
</form>
<form id="form2" name="form2" method="post" action="">
<table width="741" border="0" align="center">
<tr>
<th colspan="9" align="center" style="font-size:12px" scope="col">Xid, Name:<span>
<select name="XiD" id="XiD">
<option value="AAA">AAA</option>
<option value="BBB">BBB</option>
<option value="CCC">CCC</option>
<option value="DDD">DDD</option>
<option value="EEE">EEE</option>
<option value="FFF">FFF</option>
<option value="" selected="selected"></option>
</select>
</span><span style="font-size:12px">
<label for="date">Date:</label>
<input type="text" name="Date" id="Date" />
</span></th>
</tr>
<tr>
<th colspan="9" scope="col"> </th>
</tr>
<tr>
<th colspan="9" scope="col">
<div align="center">
<input name="action" type="button" id="RetrieveList" value="Retrieve List" />
<input name="action" type="button" id="DeletefromDB" value="Delete from DB" />
<input name="Clear" type="reset" id="Clear" value="Clear" />
</div>
<label for="Clear"></label>
<div align="center"></div></th>
</tr>
</table>
</form>
<div id="results">
</div>
</div>
and here is my 2nd php page that echoes the data into table format: Please read my comments below as I need it to clarify...
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>
<?php
require 'include/DB_Open.php';
$xid = $_POST['xid'];
$date = $_POST['date'];
$sql="SELECT ars_no, phone_number, category_1, category_2, status, create_date, resolved_date, trouble_type_priority, ban_type, employee_id_name
FROM tbl_main
WHERE employee_id_name = '" . $xid . "' AND resolved_date = '" . $date . "'";
$myData = mysql_query($sql);
echo "<table width='auto' cellpadding='1px' cellspacing='0px' border=1 align='center'>
<tr>
<th align='center'><input id=checkall name=checkall type=checkbox value='' /></th>
<th align='center'>Remedy Ticket No.</th>
<th align='center'>Phone/Incident No.</th>
<th align='center'>Category 2</th>
<th align='center'>Category 3</th>
<th align='center'>Status</th>
<th align='center'>Create Date</th>
<th align='center'>Severity</th>
<th align='center'>Ban Type</th>
<th align='center'>Resolved Date</th>
//*I have added this header so that im fetching the employee_id_name as well but just hiding it so i can delete it from my 3rd php...i used the following but still showing a very small cell on the Xid column...*
<th align='center' style='display:none'>XiD</th>
</tr>";
while($info = mysql_fetch_array($myData))
{
echo "<form action='resultgenerator_test.php' method='post'>";
echo"<tr>";
echo "<td align='center'>" . "<input type=checkbox name=checkbox value=" . " </td>";
echo "<td align='center'>" . $info['ars_no'] . "<input type=hidden name=ars_no value=" . $info['ars_no'] . " </td>";
echo "<td align='center'>" . $info['phone_number'] . "<input type=hidden name=phone_number value=" . $info['phone_number'] . " size='11' maxlength='11' /> </td>";
echo "<td align='center'>" . $info['category_1'] . "<input type=hidden name=category_1 value=" . $info['category_1'] . "' /> </td>";
echo "<td align='center'>" . $info['category_2'] . "<input type=hidden name=category_2 value=" . $info['category_2'] . "' /> </td>";
echo "<td align='center'>" . $info['status'] . "<input type=hidden name=status value=" . $info['status'] . "' /> </td>";
echo "<td align='center'>" . $info['create_date'] . "<input type=hidden name=create_date value=" . $info['create_date'] . "' /> </td>";
echo "<td align='center'>" . $info['trouble_type_priority'] . "<input type=hidden name=trouble_type_priority value=" . $info['trouble_type_priority'] . " size='1' maxlength='1' /> </td>";
echo "<td align='center'>" . $info['ban_type'] . "<input type=hidden name=ban_type value=" . $info['ban_type'] . " size='1' maxlength='1' /> </td>";
echo "<td align='center'>" . "<input type=text name=resolved_date value=" . $info['resolved_date'] . " size='8' maxlength='8' /> </td>";
echo "<td align='center'>" . "<input type=hidden name=employee_id_name value=" . $info['employee_id_name'] . "' /> </td>";
echo "</tr>";
echo "</form>";
}
echo "</table>";
include 'include/DB_Close.php';
?>
</body>
</html>
now look at the 3rd php page that ive created as u suggested and explained...please correct if u see any errors on the code:
LATEST UPDATE delete php:
<?php
require 'include/DB_Open.php';
$id = $_POST['id'];
$idtodelete = "'" . implode("','",$id) . "'";
$query = "DELETE FROM tbl_main WHERE ars_no in (" . $idtodelete . ")";
$myData = mysql_query($query);
include 'include/DB_Close.php';
?>
thanks for all the help...:)
Here what you need to do is to handle the update and delete operations with the submit button name. What you need to do is to create two submit buttons with same name but different values.
This is your form :
<form action="" method="post">
<input name="action" type="submit" id="RetrieveList" value="RetrieveList" />
<input name="action" type="submit" id="DeletefromDB" value="DeleteFromDB" />
<input name="Clear" type="reset" id="Clear" value="Clear" />
</form>
I have given same name action for the two submit buttons. Once this form is submitted you can check the $_POST['action'] in the server side.
You can do it like:
if ($_POST['action'] == 'RetrieveList') {
//retreive list functionality
} elseif ($_POST['action'] == 'DeleteFromDB') {
//delete from dB functionality.
}
UPDATE:
You need to change your form like this :
echo "<form action='resultgenerator.php' method='post'>";
echo '<input name="action" type="submit" id="DeletefromDB" value="Delete from DB" />';
echo "<table width='auto' cellpadding='1px' cellspacing='0px' border=1 align='center'>
<tr>
<th align='center'><input id=checkall name=checkall type=checkbox value='' /></th>
<th align='center'>Remedy Ticket No.</th>
<th align='center'>Phone/Incident No.</th>
<th align='center'>Category 2</th>
<th align='center'>Category 3</th>
<th align='center'>Status</th>
<th align='center'>Create Date</th>
<th align='center'>Severity</th>
<th align='center'>Ban Type</th>
<th align='center'>Resolved Date</th>
</tr>";
while($info = mysql_fetch_array($myData)) {
echo"<tr>";
echo "<td align='center'>" . "<input type='checkbox' name='checkbox[]' value='add the id here which needs to be deleted'/></td>";
echo "<td align='center'>" . $info['ars_no'] . "<input type=hidden name=ars_no value=" . $info['ars_no'] . " </td>";
echo "<td align='center'>" . $info['phone_number'] . "<input type=hidden name=phone_number value=" . $info['phone_number'] . " size='11' maxlength='11' /> </td>";
echo "<td align='center'>" . $info['category_1'] . "<input type=hidden name=category_1 value=" . $info['category_1'] . "' /> </td>";
echo "<td align='center'>" . $info['category_2'] . "<input type=hidden name=category_2 value=" . $info['category_2'] . "' /> </td>";
echo "<td align='center'>" . $info['status'] . "<input type=hidden name=status value=" . $info['status'] . "' /> </td>";
echo "<td align='center'>" . $info['create_date'] . "<input type=hidden name=create_date value=" . $info['create_date'] . "' /> </td>";
echo "<td align='center'>" . $info['trouble_type_priority'] . "<input type=hidden name=trouble_type_priority value=" . $info['trouble_type_priority'] . " size='1' maxlength='1' /> </td>";
echo "<td align='center'>" . $info['ban_type'] . "<input type=hidden name=ban_type value=" . $info['ban_type'] . " size='1' maxlength='1' /> </td>";
echo "<td align='center'>" . "<input type=text name=resolved_date value=" . $info['resolved_date'] . " size='8' maxlength='8' /> </td>";
echo "</tr>";
}
echo "</table>";
echo "</form>";
Now in your resultgenerator.php file you can check :
if ($_POST['action'] == 'DeleteFromDB') {
$ids_to_be_deleted = isset($_POST['checkbox']) ? $_POST['checkbox'] : array();
//$ids_to_be_deleted will contain all the checked id's from the other page. You can get all those values in the array. Handle the remaining operation for delete here.
}
NEW UPDATE :
So if you are using jQuery to submit your form, then it would be better to change the form submit binding to click function on the button. You can change your form to :
<link href="jquery-ui-1.10.2.custom/css/dark-hive/jquery-ui-1.10.2.custom.css" rel="stylesheet" type="text/css" />
<script type="text/javascript" src="jquery-1.9.1.min.js" ></script>
<script type="text/javascript" src="jquery-ui-1.10.2.custom/js/jquery-ui-1.10.2.custom.js" ></script>
<script type="text/javascript" src="jquery-ui-1.10.2.custom/js/jquery-ui-1.10.2.custom.min.js" ></script>
<link rel="stylesheet" href="style.css" />
<script type="text/javascript" src="SMP1_deletefromDB.js"></script>
<script type="text/javascript">
$(document).ready(function(){
$("#RetrieveList").on('click',function() {
var xid = $('#XiD').val();
var date = $('#Date').val();
$.post('resultgenerator.php',{xid:xid, date:date}, function(data){
$("#results").html(data);
});
return false;
});
$("#DeletefromDB").on('click',function() {
//get xid for delete like you do above. create a page delete.php or something and make an ajax call to some page to delete data
return false;
});
});
</script>
</head>
<body class="oneColFixCtrHdr">
<div id="container" style="width:auto">
<div id="header" style="background-color:#7BD12E">
<h1 align="left" style="color:#FFF; font-family: Arial, Helvetica, sans-serif;">PIS Ticket Tracking System</h1>
<!-- end #header --></div>
<div id="mainContent">
<h1 style="font-size:9"></h1>
<form id="form1" name="form1" method="post" action="">
<p>
<label for="Back"></label>
<input type="button" name="Back" id="Back" value="Back To Main" href="#" onclick="return backAway();" />
</p>
</form>
<form id="form2" name="form2" method="post" action="">
<table width="741" border="0" align="center">
<tr>
<th colspan="9" align="center" style="font-size:12px" scope="col">Xid, Name:<span>
<select name="XiD" id="XiD">
<option value="AAA">AAA</option>
<option value="BBB">BBB</option>
<option value="CCC">CCC</option>
<option value="DDD">DDD</option>
<option value="EEE">EEE</option>
<option value="FFF">FFF</option>
<option value="" selected="selected"></option>
</select>
</span><span style="font-size:12px">
<label for="date">Date:</label>
<input type="text" name="Date" id="Date" />
</span></th>
</tr>
<tr>
<th colspan="9" scope="col"> </th>
</tr>
<tr>
<th colspan="9" scope="col">
<div align="center">
<input name="action" type="button" id="RetrieveList" value="RetrieveList" />
<input name="action" type="button" id="DeletefromDB" value="DeleteFromDB" />
<input name="Clear" type="reset" id="Clear" value="Clear" />
</div>
<label for="Clear"></label>
<div align="center"></div></th>
</tr>
</table>
<p> </p>
</form>
<div id="results">
</div>
</div>
</body>
</html>
Here What I have done is changed the binding event on form submit and binded on click event of input type buttons. I changed type submit to button.
Now you can check on the click event of each buttons and handle the operations.
UPDATE:
Assuming that you have the retrieved list in your results div. When the user check the checkboxes and click the delete button you can handle it using this script:
$("#DeletefromDB").on('click',function() {
//get all the checked values from checkboxes
var ids = $('input[name=checkbox]:checked').map(function () {
return this.value;
}).get();
if (ids.length === 0)
return false; //show some error message
//post to delete.php file. In delete.php you can get the id's in $_POST['id'] as multidimensional array. You can handle the delete operation based on that
$.post('delete.php',{id : ids}, function(data){
//handle the message based on success or error
});
return false;
});
UPDATE :
This can be your delete.php file
$ids = isset($_POST['id']) ? $_POST['id'] : '';
if (!empty($ids)) {
//implode the id's separated by commaas
$ids_to_be_deleted = implode(',', $ids);
$query = "DELETE FROM your_table WHERE field_to_be_checked IN ($ids_to_be_deleted)";
//now run your query using mysql_query
}
NB: : mysql* functions are deprecated as of PHP 5.5.0, and will be removed in the future. Instead, the MySQLi or PDO_MySQL extension should be used
Hope this helps you :)
For your first concern, give the same name to both your submit button (e.g: 'action'), and on the server side after submit check the value : if ($_POST['action'] == 'Retrieve List') {} else if ($_POST['action'] == 'Delete from DB')
Second concern, the name of the checkbox is the key :
<input type="checkbox" name="checkbox[]" value="{$info['ars_no']}"/>
Then on server side :
foreach($_POST['checkbox'] as $checkbox) {}
You could use a dropdown list where you can chose if you want to retrieve or delete:
<select name='choseaction'>
<option value="RetrieveList">Retrieve List</option>
<option value="DeletefromDB">Delete from DB</option>
</select>
And then use a single submit button.
<INPUT TYPE ="Submit" Name ="Submit" VALUE ="Submit">
After that you can verify like this:
if ($_POST['choseaction']=='RetrieveList')
{
...
} else if ($_POST['choseaction']=='DeletefromDB')
{
...
}
Hope this helps!
Good day.

Filtering MySQL Query using PHP using checkboxes

I am working on a website for a hotel management company. On the portfolio page, I currently have a Google map with all of the hotels pinpointed and a table of the hotels all coming from a database. However, I want a form with checkboxes that correspond to the hotel brands. Selecting a checkbox will show only hotels that are that brand name. I can figure out how to do it with just one brand selected, but not with multiple.
This is the code for the form:
<form>
<div class="form-block">
<input type="checkbox" name="Courtyard" value="true" <?php if (isset($_GET["Courtyard"])) { echo "checked"; } ?> /> Courtyard<br />
<input type="checkbox" name="HolidayInnExpress" value="true" <?php if (isset($_GET["HolidayInnExpress"])) { echo "checked"; } ?> /> Holiday Inn Express<br />
<input type="checkbox" name="BestWestern" value="true" <?php if (isset($_GET["BestWestern"])) { echo "checked"; } ?> /> Best Western<br />
</div>
<div class="form-block">
<input type="checkbox" name="CrownePlaza" value="true" <?php if (isset($_GET["CrownePlaza"])) { echo "checked"; } ?> /> Crowne Plaza<br />
<input type="checkbox" name="HolidayInn" value="true" <?php if (isset($_GET["HolidayInn"])) { echo "checked"; } ?> /> Holiday Inn<br />
<input type="checkbox" name="SpringhillSuites" value="true" <?php if (isset($_GET["SpringhillSuites"])) { echo "checked"; } ?> /> Springhill Suites<br />
</div>
<div class="form-block">
<input type="checkbox" name="HamptonInn" value="true" <?php if (isset($_GET["HamptonInn"])) { echo "checked"; } ?> /> Hampton Inn<br />
<input type="checkbox" name="HomewoodSuites" value="true" <?php if (isset($_GET["HomewoodSuites"])) { echo "checked"; } ?> /> Homewood Suites<br />
<input type="checkbox" name="Independent" value="true" <?php if (isset($_GET["Independent"])) { echo "checked"; } ?> /> Independent Properties<br />
</div>
<button type="submit">Filter</button>
And the MySQL Query to display the table
<?php
if (isset($_GET["BestWestern"])) {
echo "Brand=\"Best Western\"";
}
$result = mysql_query("SELECT Name, City, State, Website FROM markers WHERE Brand LIKE '%' ORDER BY City");
echo "<table border='1'>
<tr>
<th>Hotel Name</th>
<th>City</th>
<th>State</th>
<th>Website</th>
</tr>";
while($row = mysql_fetch_array($result)) {
echo "<tr>";
echo "<td>" . $row['Name'] . "</td>";
echo "<td>" . $row['City'] . "</td>";
echo "<td>" . $row['State'] . "</td>";
echo "<td><a href='" . $row['Website'] . "'>Visit Website</a></td>";
echo "</tr>";
}
echo "</table>";
?>
Any help would be appreciated.
Simplest method would be use an WHERE ... IN () query, instead of the LIKE. e.g.
$brands = array('Brand X', 'Brand Y');
$sql = "SELECT ... WHERE Brand in ('" . implode("','", $brands) . "');";
Please note that this just an example. It is vulnerable to SQL injection attacks and should NOT BE USED as-is.

Categories