I want to display some data from table foom after select option from table factory. The select option is populated data from table factory.
The table design as the image below:
Image 1 = table factory
Image 2 = table room
(source: fbcdn.net )
(source: fbcdn.net )
Here is my code for populate select option from table Factory only:
<p>Select Factory:</p>
<?php
if($stmt = $link->query("SELECT * from factory")){
echo "<select id='exampleFormControlSelect1' name='Fac_Name' class='form-control'>";
while ($row = $stmt->fetch_assoc()) {
echo "<option value=$row[Fac_ID]>$row[Fac_Name]</option>";
}
echo "</select>";
}else{
echo $link->error;
}
?>
If I select F05, I want to display all rooms that belong to F05 which are MR1 and MR2 in a PHP table.
I like to recommend to use ajax and create new file for execute room . You factory select have id exampleFormControlSelect1
so call ajax when select change
$(document).on('change', '#exampleFormControlSelect1', function() {
var selectFactory = $(this).val();
$.ajax({
url: 'executeRoom.php', // that is optional name
method: 'GET',
dataType: 'json',
data: { facId: selectFactory },
success: function(d) {
var roomOptions = "";
for(var i in d) {
roomOptions += "<option>" + d[i].columnName + "</option>";
}
$("#roomSelect").html(roomOptions); // you should create select element for your room data
}
});
executeRoom.php
<?php
$facId = $_GET['facId'];
$result = [];
$stmt = $link->prepare("SELECT * from room where Fac_ID = ?");
$stmt->execute($facId);
foreach($stmt->fetchAll() as $row) {
$result[] = ['facId' => $row['Fac_ID'], 'facName' => $row['Fac_Name']];
}
echo json_encode($result);
Here is the answer
I'll use PDO connection
<?php
require_once 'connection.php';
$GetFactory = $conn->prepare("SELECT * FROM factory");
$GetFactory->execute();
echo '<form method="POST">';
echo '<select id="exampleFormControlSelect1" name="Fac_Name" class="form-control" onchange="this.form.submit()">';
foreach($GetFactory->fetchAll() as $factory){
echo '<option value="{$factory[Fac_ID]}">{$row[Fac_Name]}</option>';
}
echo '</select>';
echo '</form>';
if(isset($_POST['Fac_Name'])){
echo '<hr>';
$GetRoom = $conn->prepare("SELECT * FROM room WHERE Fac_ID = ?");
$GetRoom->execute([$_POST['Fac_Name']);
foreach($GetRoom->fetchAll() as $room){
echo '<p>';
echo $room['Room_Desc'];
echo '</p>';
}
}
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.