简体   繁体   中英

Using the value of a select option for the sql where clause of another select

Within the same same, how can i send the value from the first option box, and then use that value in the where clause of the second option box query?

Ie i select a client, then the second selection box will only show me options that are relevant to that client.

Ideally it would be a single page that works fluidly

Client Selection:
<?php               //OPEN DROP DOWN BOX
include("../login/dbinfo.inc.php");
$comm=@mysql_connect(localhost,$username,$password);
$rs=@mysql_select_db($database) or die( "Unable to select database"); 
$sql=   "SELECT DISTINCT ClientCode, ClientName FROM tbl_client ORDER BY ClientCode";
$result = mysql_query($sql);
echo "<select name='ClientCode'>";
while ($row = mysql_fetch_array($result)) {
echo "<option value='" . $row['ClientCode'] ."'>" . $row['ClientName'] ."</option>;
}
echo "</select><br>";   //CLOSE DROP DOWN BOX   

?><br>

Vessel Selection:
<?php               //OPEN DROP DOWN BOX
$client = $_GET["$client"];//assign client code from first drop down to this value & use in query 'WHERE' clause

include("../login/dbinfo.inc.php");
$comm=@mysql_connect(localhost,$username,$password);
$rs=@mysql_select_db($database) or die( "Unable to select database"); 
$sql=   "SELECT VesselName  FROM tbl_import WHERE ClientCode='".$client."' ORDER BY VesselName";
$result = mysql_query($sql);
echo "<select name='VesselName'>";
while ($row = mysql_fetch_array($result)) {
echo "<option value='" . $row['VesselName'] ."'>" . $row['VesselName'] ."</option>";
}
echo "</select><br>";   //CLOSE DROP DOWN BOX                                   
?>

PHP is a server side language - all of the queries execute before it's received by the browser. If you want the content of your menu to change based on your first selection (the client), you'll either need to submit the form after you've selected the client OR use javascript to populate the second menu after the first menu has received a selection.

Second note - you're using mysql functions - those have been deprecated in PHP5 and removed in PHP7; look into at least updating your code to use mysqli functions.

Third note - you're inserting user data directly into your queries, meaning your opening your site to SQL injections. You can avoid that by using prepared statements and bound parameters through mysqli or (better still) pdo functions to access your database.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM