简体   繁体   中英

Dynamic MySQL query depending on dynamic PHP dropdown

I am looking for help with how to fetch different MySQL queries from database depending on the dynamic PHP dropdown. Below is everything I have done so far (1. created Database, 2. created PHP dynamic dropdown, 3. the struggle part - how to get the HTML/PHP form change it´s MySQL query depending on the dynamic drop-down selected in step 2).

Here is my Create Database:

CREATE TABLE computers (
id           int(3) NOT NULL auto_increment primary key, 
pc_make      varchar(25) NOT NULL default '', 
pc_model      varchar(25) NOT NULL default ''
) ENGINE=InnoDB DEFAULT CHARSET=utf8;


INSERT INTO computers VALUES (1, 'Dell', 'Latitude'); 
INSERT INTO computers VALUES (2, 'Dell', 'Inspiron'); 
INSERT INTO computers VALUES (3, 'HP', 'Pavilion'); 
INSERT INTO computers VALUES (4, 'HP', 'Spectre');
INSERT INTO computers VALUES (5, 'Lenovo', 'Thinkpad'); 
INSERT INTO computers VALUES (6, 'Lenovo', 'Ideapad');

Here is the part that produces the dynamic drop-down (it gives me the result of 3 distinct records: "Dell", "HP" and "Lenovo"):

<?   

 $connect = mysqli_connect('localhost', '', '', ''); 
 $sql="SELECT DISTINCT(pc_make) AS pc_make FROM computers ORDER BY pc_make ASC"; 
 $result  = mysqli_query($connect, $sql);  

 if(mysqli_num_rows($result) > 0){  
 $output= '<select name="listofpcmakes">';
 while($rs = mysqli_fetch_array($result)){  

  $output.='<option value="'.$rs['id'].'">'.$rs['pc_make'].'</option>';

  }
}
$output.='</select>';
echo $output;
?>

And below is my attempt to display only the records that match the selected pc_make (for instance Dell, which should result in 2 records) from the dynamically created dropdown. Looks like I am only hitting the wall here.

<html>
<body>

         <form id="my_form" name="my_form" method="post"> 
         <table class="table">
              <thead>
                <tr>
                  <th>id</th>
                  <th>pc_make</th>
                  <th>pc_model</th>               
                </tr>
              </thead>
              <tbody>

<?PHP

 $sql_final="SELECT * FROM computers WHERE pc_make = (how to capture the 'selected pc_model' from the dynamically generated dropdown???) "; 
 $result_final  = mysqli_query($connect, $sql_final); 

                    while ($myrow = mysqli_fetch_array($result_final)) 

                    {
                  ?>
                <tr>
                  <td><?PHP echo $myrow["id"]; ?></td>
                  <td><?PHP echo $myrow["pc_make"]; ?></td>
                  <td><?PHP echo $myrow["pc_model"]; ?></td>                  
                </tr>
         <?PHP
              }
                  ?>


</body>               
</html>               

To restate the issue, how should I build the HTML form part, which only fetches records (pc_make, pc_model) for a single manufacturer (Dell, HP, or Lenovo) which is selected from the dynamically generated dropdown. I am trying to avoid creating static mysql queries, since the manufacturers list may considerably change in the future.

Thanks all in advance for providing helping hand...

When you select an option from your dropdown and submit the form, the result will be in $_POST superglobal . So, you need to check $_POST and retrieve the value of your dropdown.

At the top of the page:

if ($_SERVER['REQUEST_METHOD'] == 'POST') {
    $selected_pc_model = $_POST['listofpcmakes'];
}

You can now use $selected_pc_model in your SQL query:

$sql_final="SELECT * FROM computers WHERE pc_make = $selected_pc_model";

A more complete example using the code you submitted above:

<?php
if (($_SERVER['request_method']) == 'POST') { // Checking to see if form is submitted
    $selected_pc_model = $_POST['listofpcmakes']; // Getting the selected PC model value
}
?>
<html>
<body>

<form id="my_form" name="my_form" method="post">
<table class="table">
    <thead>
    <tr>
        <th>id</th>
        <th>pc_make</th>
        <th>pc_model</th>
    </tr>
    </thead>
    <tbody>

<?php
if (isset($selected_pc_model)) { // if there is a $selected_pc_model
    $sql_final="SELECT * FROM computers WHERE pc_make =" . $selected_pc_model;
    $result_final  = mysqli_query($connect, $sql_final);

    while ($myrow = mysqli_fetch_array($result_final)) {
?>
        <tr>
            <td><?PHP echo $myrow["id"]; ?></td>
            <td><?PHP echo $myrow["pc_make"]; ?></td>
            <td><?PHP echo $myrow["pc_model"]; ?></td>
        </tr>
<?php
    }
} else { // else if there is NOT a $selected_pc_model
        echo '<tr>
                <td>Error: PC Model is not selected.</td>
              </tr>';
}
?>
    </tbody>
</table>

</body>
</html>

There is more to do when you write this kind of code such as data validation and error checking etc., but this should be enough to get you going. For more, you should read PHP tutorials and/or get a couple of courses.

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