iT邦幫忙

0

網頁下拉是選單連結資料庫抓資料

  • 分享至 

  • twitterImage

各位大神好~
目前我已經將下拉是選單中的option連上資料庫了,但我的需求是點下他讓他會在下面的div出現資料庫中的值,這樣說有點難懂,以下是我目前做的:

1.PHP

<html>
<head>
  <title>get select value</title>
</head>
 
<script>
function print_value() {
	
	document.getElementById("result").innerHTML = document.getElementById("number").value
}
</script>
 
<body>
 
<select name="number" id="number" onchange="print_value();">
     <?php
           $conn=mysqli_connect("localhost", "root","","資料庫名稱");
           $sql = "SELECT DISTINCT date FROM attend";
           $result = $conn->query($sql);
           while($row = $result->fetch_assoc()) 
      {?>
    
    
<option value="<?php echo $row['date'];?>"><?php echo $row['date'];?></option>
<?php } ?>
</select>
 
 
<!-- 印出結果 -->
<div id="result"></div>
 
</body>
</html>

2.資料表(共三個欄位,S_id及date會重複,以三個人及兩個日期做舉例):
S_id date attnum
107001 02/22 1
107002 02/22 0
107003 02/22 1
107001 03/01 0
107002 03/01 1
107003 03/01 1

3.我想要的樣子:
https://ithelp.ithome.com.tw/upload/images/20210918/20141966NxlPdfShPT.png

求求各位大神了!

archer9080 iT邦研究生 4 級 ‧ 2021-09-20 08:59:15 檢舉
正常作法如@Hankz 前輩所述,前端(HTML)顯示日期,使用者選擇日期後利用ajax跟資料庫取得對應的資料

非正常(普遍(?))作法就group by & group_concat取得日期對應的所有資料且處理後塞在value,js取得值處理後再顯示至對應區域

要不然在result內弄個table,一開始就將質料全抓出並放在對應的cell內並隱藏此table,利用選中的值去遍歷tr,找對應的cell中有沒有符合的資料,有的話再顯示

不過建議按正常的方式後續比較不容易遇到問題
hoo0723 iT邦新手 5 級 ‧ 2021-09-21 11:01:03 檢舉
好的,謝謝您~
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

1 個回答

2
Hankz
iT邦新手 2 級 ‧ 2021-09-18 21:20:45

用PHP寫一支API
然後用ajax去接回傳值後
再放到畫面上

如果以上看不懂
那你就需要去弄懂「API」、「AJAX」這兩個東西
才有辦法滿足這類的需求

以下參考作法

PHP(api.php):

$date = $_POST['date'];

// 從DB撈資料,我這裡先寫死
$response[0]['S_id'] = '107001';
$response[0]['attnum'] = 1;
$response[1]['S_id'] = '107001';
$response[1]['attnum'] = 1;
$response[2]['S_id'] = '107001';
$response[2]['attnum'] = 1;

echo json_encode($response);

JavaScript(有使用jQuery):

$("#number").change(function() {
    $.post(
        "api.php",
        "date": $(this).val(),
        function(result) {
            html = "<tr>";
            result.forEach(function(item) {
                // 在這邊把資料塞到畫面上
                html += "<td>" + item.S_id + "</td>";
                html += "<td>" + item.attnum + "</td>";
            });
            html += "</tr>";
            $("#YOUR_TABLE_ID").html(html);
        },
        "json"
    );
});

以上純手打可能會有錯字,請見諒

hoo0723 iT邦新手 5 級 ‧ 2021-09-20 10:07:59 檢舉

謝謝Hankz的解答!需要來研究一下~如果有不懂再請教您~中秋節快樂~

我要發表回答

立即登入回答