SQL UPDATE select w/ multiple to a PHP array - javascript

I'm aware of the SQL injection issues in this code. I am however focusing on just trying to get form to update the mySQL server. I have two select boxes that are populated. I can transfer the equipment back and forth between the two. However when I go to update It does not work. PLEASE HELP ME!
HERE is FORM:
$connection = mysql_connect('#', '#', '#');
mysql_select_db('#');
$techequipment = "SELECT serial, type_id FROM tbl_assets WHERE user_id = {$_GET ['TechID']} AND date_installed IS NULL AND date_returned IS NULL AND metro_date_returned IS NULL ORDER BY type_id, serial";
$techresult = mysql_query($techequipment);
$jobequipment = "SELECT serial, type_id FROM tbl_assets WHERE account_number = {$_GET ['JobNum']} ORDER BY type_id, serial";
$jobresult = mysql_query($jobequipment);
$link = array($_GET ['JobNum'])
?>
<title>Assign Equipment</title>
<table align="center">
<form action="assigned_equipment.php?<? echo http_build_query($link)?>" method="POST">
<tr>
<td><center><b><?php echo "Tech #"; echo $_GET ['TechID']; echo " Assigned Equipment"; ?></b></center></td>
<td></td>
<td><center><b><?php echo "Job #"; echo $_GET ['JobNum']; echo " Assigned Equipment"; ?></b></center></td>
</tr>
<tr>
<td>
<select name="tech[]" size=20 multiple id="list1" STYLE="width: 350px">
<?php $i=0; while($row = mysql_fetch_array($techresult)) { ?>
<option value="<?=$row["serial"];?>"> <?=$row["type_id"]." - ".$row["serial"];?></option>
<?php $i++; } ?> </select>
</td>
<td>
<center><input type="button" id="btnAdd" value="Transfer >>"/></center>
<center><input type="button" id="btnRemove" value="<< Transfer"/></center>
</td>
<td>
<select name="job[]" size=20 multiple id="list2" STYLE="width: 350px">
<?php $i=0; while($row = mysql_fetch_array($jobresult)) { ?>
<option value="<?=$row["serial"];?>"> <?=$row["type_id"]." - ".$row["serial"];?></option>
<?php $i++; } ?> </select>
</td>
</tr>
<tr>
<td colspan="2">
</td>
<td>
<center><input type="submit" value="SUBMIT"/></center>
</form>
</td>
</tr>
<tr>
<td colspan="3">
<center>Multi Select: Press & hold [CTRL] while clicking on the items.</center>
</td>
</tr>
<tr>
<td colspan="3">
<center>EXIT</center>
</td>
</tr>
</table>
<script src="js/jquery-2.2.0.js" type="text/javascript"></script>
<script type="text/javascript">
$(document).ready(
function () {
//TAKE EQUIPMENT FROM TECH AND PUT IT IN JOB BOX
$('#btnAdd').click(
function (e) {
$('#list1 > option:selected').appendTo('#list2');
e.preventDefault();
});
//TAKE EQUIPMENT FROM JOB AND PUT IT IN TECH BOX
$('#btnRemove').click(
function (e) {
$('#list2 > option:selected').appendTo('#list1');
e.preventDefault();
});
});
</script>
Here is my assigned_equipment.php file:
<?php
$connection = mysql_connect('#', '#', '#')
or die('Could not connect: ' .mysql_error());
mysql_select_db('#');
$equipmentquery="UPDATE tbl_assets SET date_installed = curdate(), account_number = {$_GET['0']} WHERE serial = $_POST['job']";
$techquery="UPDATE tbl_assets SET date_installed = curdate(), account_number = {$_GET ['0']} WHERE serial = $_POST['tech']";
?>

Ok, you are right it seems to be the case that "0" is a valid variable name to submit via $_GET or $_POST. So this is not a problem.
But your problem is that $_POST['job'] is an array.
You try to do this:
$equipmentquery = ""
. "UPDATE tbl_assets "
. "SET date_installed = curdate(), "
. "account_number = {$_GET['0']} "
. "WHERE serial = $_POST['job']";
While $_POST['job'] is an array you cannot do it like this!
Please try the following:
$jobnum = (int)$_GET['0'];
$job_arr = $_POST['job'];
if(($jobnum > 0) && is_array($job_arr) && (count($job_arr) > 0)) {
$equipmentquery = ""
. "UPDATE tbl_assets "
. "SET date_installed = curdate(), "
. "account_number = ".$jobnum." "
. "WHERE "
. 'serial IN ("'.implode('","',$job_arr).'") ';
}
Ok what happens here?
I suspect that your serial holds the values posted in job array.
So you want to update each row where your serial matches the posted values in your array.
In case of your $_POST: Array ( [job] => Array ( [0] => gi4416ncd876 [1] => GI4521NA3391 [2] => M40719GD6274 [3] => PAEH01734539 ) ) and your $_GET: Array ( [0] => 113852 ) it will result in the following query:
UPDATE tbl_assets
SET date_installed = curdate(),
account_number = 113852
WHERE serial IN ("gi4416ncd876","GI4521NA3391",
"M40719GD6274","PAEH01734539")
Ok now you have a working query.
Not it is time to execute it!!!
therefore you need to:
$result = mysql_query ( $equipmentquery );
this is the important line, you are missing!
Finally your code may look like this:
<?php
$connection = mysql_connect('#', '#', '#')
or die('Could not connect: ' .mysql_error());
mysql_select_db('#');
$jobnum = (int)$_GET['0'];
$job_arr = $_POST['job'];
$tech_arr = $_POST['tech'];
if(($jobnum > 0) && is_array($job_arr) && (count($job_arr) > 0)) {
$equipmentquery = ""
. "UPDATE tbl_assets "
. "SET date_installed = curdate(), "
. "account_number = ".$jobnum." "
. "WHERE "
. 'serial IN ("'.implode('","',$job_arr).'") ';
$result1 = mysql_query ( $equipmentquery );
}
if(($jobnum > 0) && is_array($tech_arr) && (count($tech_arr) > 0)) {
$techquery = ""
. "UPDATE tbl_assets "
. "SET date_installed = curdate(), "
. "account_number = ".$jobnum." "
. "WHERE "
. 'serial IN ("'.implode('","',$job_arr).'") ';
$result2 = mysql_query ( $techquery );
}
When this works, you should directly switch to mysqli or pdo!
mysql_ functions are deprecated and not present any more in the latest php version! You should really care about sql injection! So use prepared statements to clean up your input data!!! There are various tutorials out there!!! DO NOT USE THIS CODE IN A LIVE ENVIRONMENT

Related

update echo "select option " on mysql

I have a form that updates the adds to the table. This table is retrieved live. which means once submitting the form you can view the content on the table. I added a select option drop down on the table content. I am not sure how to get this info in back to mysql once the user chooses his option. As seen in the code my file is a PHP file.
my select option is updates by javascript but it does not update mysql.
Kindly guide me. Thank you
while($row = mysqli_fetch_assoc($resultset))
{
echo "<tr id=\"row\">
<td class=\"fname\" data-id1=".$row["contact_id"]." contenteditable>" . $row['fname'] ." </td>
<td class=\"lname\" data-id2=".$row["contact_id"]." contenteditable>" . $row['lname']. "</td>
<td>" . $row['contact']."</td>
<td>
<select id4=".$row['contact_id']." name=\"rsvp\" onchange = \"fetch_select(this.value)\">
<option name=\"not-done\" value=\"not-done\">Not done</option>
<option name=\"attending\" value=\"attending\">Attending</option>
<option name=\"not-attending\" value=\"not-attending\">Not-attending</option>
<option name=\"maybe\" value=\"maybe\" selected>Maybe</option>
</select>
</td>
<td><button id3=".$row['contact_id']." name=\"button\"><i class=\"fa fa-trash-o\" aria-hidden=\"true\"></i></button>
<tr>";
}
echo "</table>";
mysqli_close($con);
?>
$('select').on('change', function()
{
// Show an alert
alert( "The new value of the select is " + $(this).val() );
var id=$(this).attr("id4");
var val=$(this).val();
function fetch_select(val ,id)
{
$.ajax({
url:"updateselect.php",
method:"POST",
data:{rsvp:val , id:id},
dataType:"text",
success:function(data){
alert(data);
}
});
}
});
<?php
$connect = mysqli_connect("localhost", "root", "", "registration");
$id = $_POST["id"];
$rsvp = $_POST["val"];
$sql = "UPDATE guestlist SET rsvp ='".$rsvp."' WHERE contact_id='".$id."'";
if(mysqli_query($connect, $sql))
{
echo 'Data Updated';
}
?>
You want to create a form surrounding your dropbox; now you can either submit it using ajax or just submit it to a different page, your call.
It would look something like this:
Note: Add a name param to your select so you can actually get it using $_POST and handle the data.
<form method="post" action="rsvp_handler.php">
<?php
while($row = mysqli_fetch_assoc($resultset))
{
echo "<tr id=\"row\">
<td class=\"fname\" data-id1=".$row["contact_id"]." contenteditable>" . $row['fname'] ." </td>
<td class=\"lname\" data-id2=".$row["contact_id"]." contenteditable>" . $row['lname']. "</td>
<td>" . $row['contact']."</td>
<td>
<select name='rsvp' id='rsvp'>
<option value=\"not-done\">Not done</option>
<option value=\"attending\">Attending</option>
<option value=\"not-attending\">Not-attending</option>
<option value=\"maybe\" selected>Maybe</option>
</select>
</td>
<td><button id3=".$row['contact_id']." name=\"button\"><i class=\"fa fa-trash-o\" aria-hidden=\"true\"></i></button>
<tr>";
}
echo "</table>";
mysqli_close($con);
?>
<button type="submit" name="submit">Submit</button>
</form>
Then for the rsvp_handler.php page just take the post result and then send the wanted data to your database:
if (isset($_POST['submit']))
{
$rsvp = $_POST['rsvp'];
//... any other elements
// create your query here
$sql = "INSERT INTO " . $table . " (rsvp, row2, row3) VALUES (?, ?, ?)";
// best way is to create prepared statements
if($stmt = $mysqli->prepare( $sql ))
{
// bind the params
$stmt->bind_param('sss', $rsvp, $val2, $val3);
// execute the query
$stmt->execute();
// close the connection
$stmt->close();
}
}
Hi I found the answer to the solutions.
My ajax need to have a separate function.

How do I email an html table containing mysql result data with a button in php?

Sorry if this is a poor description, I am relatively new to this.
I am developing a web tool which displays the results of mysql data filtered by a date range in an html table. I have an input and button which allows the user to input an email address to send the table data to. The problem is I am having trouble passing the html table data correctly to my php page to be emailed.
I've tried various methods with AJAX and Javascript, but nothing is working. At one point I was able to pass the table data, but not the inputted email (or vice versa); never both simultaneously. I need to be able to pass both the email that has been inputted as well as the data in the html table preferably reserving the table format as well for a cleaner look). Any help and/or insight is greatly appreciated. Apologies if this code is improper and/or wrong.
Relevant PHP:
<!-- download2csv button -->
<div>
<form action="getCSV.php" method="post">
<input type="hidden" name="csv_text" id="csv_text_computers">
<button class="btn btn-app btn-primary btn-xs no-radius" type="submit" onclick="getCSVDataComputers()">
<i class="icon-save"></i></button>
</form>
<!-- email button -->
<form action="mailto.php" method="post">
Email: <input type="text" name="einame" id="eiid" placeholder="example#example.com">
<button class="btn btn-app btn-info btn-xs no-radius" type="submit" name="ebname" id="ebid" onclick="mailer()">
<i class="icon-envelope"></i></button>
</form>
</div>
</div>
<!-- data table header -->
<div class="table-responsive">
<table id="table-computers1" name="table-computers" class="table table-striped table-bordered table-hover">
<thead>
<tr>
<th>Item Name</th>
<th>RFID Number</th>
<th>Link</th>
<th>Delivery Date</th>
</tr>
</thead>
<tbody>
<?php
foreach ($infocoms as $infocom)
{
//variables for glpi url
$itemtype = $infocom['itemtype'];
$items_id = $infocom['items_id'];
$url = "https://null.null.com/front/" . $itemtype. ".form.php?id=" . $items_id;
?>
<tr>
<?php
// database connection
$conn = mysqli_connect('null', 'null', 'null');
mysqli_select_db($conn, 'glpi');
if ($infocom['itemtype'] == "peripheral") {
$query = "SELECT glpi_peripherals.name AS devicename, TRIM(LEADING '0' FROM glpi_peripherals.otherserial) AS otherserial FROM glpi_peripherals INNER JOIN glpi_infocoms ON glpi_peripherals.id = glpi_infocoms.items_id WHERE glpi_infocoms.items_id = $infocom[items_id] AND glpi_infocoms.itemtype = 'peripheral'";
$result = mysqli_query($conn,$query) or die(mysqli_error($conn));
$devices = $result->fetch_assoc();
echo "<td>$devices[devicename]</td>";
echo "<td><center>$devices[otherserial]</center></td>";
} elseif ($infocom['itemtype'] == "computer") {
$query = "SELECT glpi_computers.name AS compname, TRIM(LEADING '0' FROM glpi_computers.otherserial) AS otherserial FROM glpi_computers INNER JOIN glpi_infocoms ON glpi_computers.id = glpi_infocoms.items_id WHERE glpi_infocoms.items_id = $infocom[items_id] AND glpi_infocoms.itemtype = 'computer'";
$result = mysqli_query($conn,$query) or die(mysqli_error($conn));
$computers = $result->fetch_assoc();
echo "<td>$computers[compname]</td>";
echo "<td><center>$computers[otherserial]</center></td>";
} elseif ($infocom['itemtype'] == "monitor") {
$query = "SELECT glpi_monitors.name AS viewname, TRIM(LEADING '0' FROM glpi_monitors.otherserial) AS otherserial FROM glpi_monitors INNER JOIN glpi_infocoms ON glpi_monitors.id = glpi_infocoms.items_id WHERE glpi_infocoms.items_id = $infocom[items_id] AND glpi_infocoms.itemtype = 'monitor'";
$result = mysqli_query($conn,$query) or die(mysqli_error($conn));
$monitors = $result->fetch_assoc();
echo "<td>$monitors[viewname]</td>";
echo "<td><center>$monitors[otherserial]</center></td>";
} elseif ($infocom['itemtype'] == "networkequipment") {
$query = "SELECT glpi_networkequipments.name AS netname, TRIM(LEADING '0' FROM glpi_networkequipments.otherserial) AS otherserial FROM glpi_networkequipments INNER JOIN glpi_infocoms ON glpi_networkequipments.id = glpi_infocoms.items_id WHERE glpi_infocoms.items_id = $infocom[items_id] AND glpi_infocoms.itemtype = 'networkequipment'";
$result = mysqli_query($conn,$query) or die(mysqli_error($conn));
$networks = $result->fetch_assoc();
echo "<td>$networks[netname]</td>";
echo "<td><center>$networks[otherserial]</center></td>";
} elseif ($infocom['itemtype'] == "printer") {
$query = "SELECT glpi_printers.name AS printname, TRIM(LEADING '0' FROM glpi_printers.otherserial) AS otherserial FROM glpi_printers INNER JOIN glpi_infocoms ON glpi_printers.id = glpi_infocoms.items_id WHERE glpi_infocoms.items_id = $infocom[items_id] AND glpi_infocoms.itemtype = 'networkequipment'";
$result = mysqli_query($conn,$query) or die(mysqli_error($conn));
$printers = $result->fetch_assoc();
echo "<td>$printers[printname]</td>";
echo "<td><center>$printers[otherserial]</center></td>";
} else {
// error handling for null entries
echo "1 or more items were not found";
}
// end data loop and close mysql connection
mysqli_close($conn);
?>
<td><a target=_blank href=$url><?php echo $url; ?></a></td>
<td><center><?php echo $infocom['ddate']; ?></center></td>
</tr>
<?php
}
?>
</tbody>
</table>
</div>
</form>
</div>
<?php
} else {
echo "<center><p style='font-size:125%;'>Please select a date range to submit.</p></center>";
}
error_log("\n");
?>
Relevant Javascript:
<script type="text/javascript">
jQuery(function($) {
var oTable1 = $('#table-computers').dataTable( {
"aLengthMenu": [[10, 25, 100, -1], [10, 25, 100, "All"]],
"iDisplayLength": -1,
"aoColumns": [
{ "bSortable": true },
null, null,null,
] } );
})
function getCSVDataComputers(){
var csv_value=$('#table-computers').table2CSV({delivery:'value'});
$("#csv_text_computers").val(csv_value);
}
</script>
<script type="text/javascript">
function mailer()
{
var tableContent=document.getElementById("table-computers").innerHTML;
alert(tableContent); // This works, but data does not echo in mailto.php
$.post('mailto.php',{content:tableContent},function(data) {
});
}
</script>
Mailto PHP page:
<?php
$mailto = $_POST['einame'];
$table = $_POST['tableContent'];
$headers .= 'MIME-Version: 1.0' . "\r\n";
$headers .= 'From: Test <test#example.com>' . "\r\n";
$headers .= 'Content-type: text/html; charset=iso-8859-1' . "\r\n";
if (isset($mailto)) {
mail($mailto,"GLPI Notifications",$table,$headers);
echo "Mail sent successfully to $mailto." . "\r\n";
} else {
echo "Mail was not sent." . "\r\n";
}
?>
<br>
Home Page
<br>
<?php
echo $table; // Displays nothing
error_log("\n");
?>
finally figured it out. updated code:
function mailer() {
var tableContent=document.getElementById("table-computers").innerHTML;
// alert(tableContent); confirmation
$.post("mailto.php",{ "content": $("#bmailto").val(tableContent) },function(data) {
});
}

How can I extract JSON data from PHP and display it in a datatable?

I want to get reports from my database by using PHP via turning it into JSON format and displaying it with AJAX JQuery. But I can't seem to pass the data correctly. Can somebody please tell me my fault?
Here is my code view:
$(document).ready(function() {
$("#searchOverall").click(function() {
var ay = $("#Overall_acadyear").val();
var year = $("#Overall_year").val();
if (ay === undefined || ay == '') {
alert("Select Academic year.");
} else if (year === undefined || year == '') {
alert("Select year level.");
} else {
$.ajax({
url: "js/overallreport.php",
dataType: "json",
data: "ay=" + ay + "&year=" + year,
success: function(data) {
//left this blank because I am not sure of what I am doing.
//I used $.getJSON and $.each
},
error: function() {
alert('Cannot retrieve data from server.');
}
}); //ajax
} //else
}); //btnOverall
});
//This is the JS FILE
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div class="form-group col-sm-4">
<select class="form-control" id="Overall_acadyear">
<option value='' active>Select AY</option>
<?php $r->selectAcademicYear(); ?>
</select>
<select class="form-control col-sm-4" id="Overall_year" align="right">
<option value='' active>Select year level</option>
<?php $r->selectYear(); ?>
</select>
<div class="form-group">
<button type="button" class="control-label btn-success" id="searchOverall" name='createAccount'>Search</button>
<button type="reset" class="control-label btn-danger" id="reset">Clear Fields</button>
</div>
</th>
</tr>
<tr>
<th>Student Number</th>
<th>Student Name</th>
<th>Section</th>
<th>Status</th>
</tr>
</thead>
<tbody id="tableBody">
</tbody> <!--This is the view file -->
<?php
require($_SERVER['DOCUMENT_ROOT']."/finalsis/include/config.php");
include_once($_SERVER['DOCUMENT_ROOT']."/finalsis/include/class.utility.php");
header("Content-Type: application/json");
$ay = $_GET['ay'];
$year = $_GET['year'];
$ay = $obj->cleanString($ay);
$year = $obj->cleanString($year);
$conn = mysqli_connect(db_server,db_user,db_password,db_database);
$ay = mysqli_escape_string($conn,$ay);
$year = mysqli_escape_string($conn,$year);
$selectSQL = "SELECT studentlevel_student, student_fname, student_mname, student_lname,
section_name, student_status FROM tblstudentlevel inner join
tblstudent on studentlevel_student = student_number inner join
tblyearsection on studentlevel_ys = ys_id WHERE studentlevel_acadyear = '" .$ay."' AND year_name = '" .$year. "'";
$result = mysqli_query($conn,$selectSQL);
$output = '{"student": [';
while($rs = mysqli_fetch_array($result)){
$name = $obj->getFullName($rs['student_fname'],$rs['student_mname'],$rs['student_lname']);
$output .= '{"sno":"' .$rs['studentlevel_student']. '", ';
$output .= '"name":"' .$name. '", ';
$output .= '"section":"' .$rs['section_name']. '",';
$output .= '"status":"' .$rs['student_status']. '"},';
}
$output .= "]}";
mysqli_close($conn);
echo json_encode($output);
//This is where my data gathering happens. ?>
Problem is in the following line:
echo json_encode($output);
json_encode needs an array. You are passing string.
$jsonData = array();
while($rs = mysqli_fetch_array($result)){
$name = $obj->getFullName($rs['student_fname'],$rs['student_mname'],$rs['student_lname']);
$jsonData[] = array(
'sno' => $rs['studentlevel_student'],
'name' => $name,
);
}
echo json_encode($jsonData);

unable to compare data from database to array of strings

i have a program where i need to insert words as much as i wish and then those words will be checked through database, if it is present in database , it should return how many words where present in database.
please tell me what is wrong with this code, it is not returning the number of similar entries to database
<html>
<head>
<script language="javascript" type="text/javascript">
// Pre-defined text:
var newtext = "This is the new text";
// Drop-Menu:
var newtext = myform.mymenu.options[myform.mymenu.selectedIndex].value;
// Prompt:
var newtext = prompt('Enter New Text Here:', '');
function addtext() {
var newtext = document.myform.inputtext.value;
document.myform.outputtext.value += newtext+' ';
}
</script>
</head>
<body>
<form name="myform" action="" method="post">
<table border="0" cellspacing="0" cellpadding="5"><tr>
<td><textarea name="inputtext"></textarea></td>
<input type="radio" name="placement" value="append" checked> Add to Existing Text<br>
<td><p><input type="radio" name="placement" value="replace"> Replace Existing Text<br>
<input type="button" value="Add New Text" onClick="addtext();"></p>
</td>
<td><textarea name="outputtext"></textarea></td>
</tr></table>
<input type="submit"/>
</form>
<?php
$string=$_POST['outputtext'];
$array=array();
$array=explode(';',$string);
# $db=new mysqli('localhost','root','','words');
if(mysqli_connect_errno())
{
echo 'Error:Could not connect to the database';
}
else
echo 'connected';
$db->select_db('words');
$count = 0;
foreach($array as $s)
{
$query="select * from collection where word LIKE '%".$s."%'";
$result=$db->query($query);
if($result)
$count += $db->num_rows;
}
echo $count;
$db->close();
?>
</body>
</html>
$count = 0;
foreach($array as $s)
{
$query="select count(*) as num_matched from collection where word LIKE '%".$s."%'";
$result=$db->query($query) or die($db->error);
$row = $result->fetch_assoc();
$count += $row['num_matched'];
}
echo $count;
You should also switch to parametrized queries instead of using the input directly.
$stmt = $db->prepare("select count(*)
FROM collection
WHERE word LIKE CONCAT('%', ?, '%')");
$stmt->bind_param("s", $s);
$count = 0;
foreach ($array as $s) {
$result = $stmt->execute();
$stmt->bind_result($num_matched);
$stmt->fetch();
$count += $num_matched;
}
echo $count;
$db->num_rows is already the number of rows... You don't need to manually count them.
its not feasible to run query in for loop so, you can try below solution,
$array=array('abc','xyz','lmn','pqr');
$query="select word from collection where word LIKE '%".$s."%'";
$result=$db->query($query);
while ( $row = mysql_fetch_array($result) )
{
$tblarray[] = $row['word'];
}
foreach($tblarray as $k => $v)
{
foreach($array AS $key => $value)
{
if (strpos($v, $value) !== false)
{
$finalarray[] = $v;
}
}
}
echo sum($finalarray);

Return dynamic select to null onChange

I have two select boxes, the second of which is dependent upon the selection in the first. I want to get the second select box (course) to have a value of null when the first box (subject) is changed. Any help on accomplishing this would be greatly appreciated.
This is what I have tried:
Javascript:
function autoSubmit() {
var formObject = document.forms['theForm'];
formObject.submit();
}
PHP:
<form name="theForm" method="get">
<select name="subject" onChange="autoSubmit();">
<option value="null">Select a Subject...</option>
<php
$sql = "SELECT DISTINCT subj_name, subj_id FROM table1 ORDER BY subj_name
$result = mysql_query($sql) or die ("couldn't execute query");
while($row = mysql_fetch_array($result))
{
echo ("<option value=\"$row[subj_id]\" " . ($subject == $row["subj_id"] ? "
selected" : "") . ">$row[subj_name]</option>");
}
?>
</select>
<select name="course" onChange="autoSubmit();">
<option value="null">All Courses</option>
<php
if($subject != null && is_numeric($subject))
{
$sql = "SELECT DISTINCT subj_id, course_id, course_name FROM table1
WHERE subj_id = $subject ORDER BY course_name
$result = mysql_query($sql);
while($row = mysql_fetch_array($result))
{
echo ("<option value=\"$row[course_id]\" " . ($course == $row["course_id"] ?
" selected" : "") . ">$row[course_number] - $row[course_name]</option>");
}
}
?>
</select>
</form>
You can put in the onChange of the first select, before the autoSubmit() :
this.form.course.value='null';
or
this.form.course.selectedIndex=0;
This way the value on the get will be ?subject=[the_subject]&course=null ( and then $course == $row["course_id"] will be false ).
( http://jsfiddle.net/HMT34/ )

Categories