将MYSQL表中的数据输出到HTML表单中,具体取决于用户选择 [英] Output Data From MYSQL Table Into HTML Form Depending On User Choice

查看:45
本文介绍了将MYSQL表中的数据输出到HTML表单中,具体取决于用户选择的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个MYSQL表(roomcost),其中包含出租房间的费用.

I have a MYSQL table (roomcost) that holds the costs of hiring rooms.


costID  Room    Cost
1       room1   15
2       room2   30
3       room3   50

rsRoomCost SQL是: SELECT * FROM roomcost

rsRoomCost SQL is: SELECT * FROM roomcost

HTML表单具有复选框,允许承租人选择1号房,2号房或3号房.承租人可以租用一个,任意两个或全部三个房间.

The HTML form has checkboxes that allow the hirer to make the choice of Room 1, Room 2 or Room 3. The hirer can hire one, any two or all three rooms.

<input type="checkbox" name="room1" value="room1" onClick="Check()">Room 1</div>
<input type="checkbox" name="room2" value="room2" onClick="Check()">Room 2</div>
<input type="checkbox" name="room3" value="room3" onClick="Check()">Room 3</div>

该表格还有一个输入框(一旦我开始工作,它就会被隐藏),每个输入框将用表中的适当费用填充.提交表单后,租房者记录将保留该房间的选择以及该人在租房时所支付的费用.

The form also has an input box (that will be hidden, once I get it working) for each room that will be filled with the appropriate cost from the table. When the form is submitted, the hirers record would hold the choice of room(s) and cost paid by that hirer at the time of hiring.

用于检查是否选中了特定复选框的JS脚本,并将成本输出到相关的输入框.

The JS script that checks if a particular checkbox is selected and would output the cost to the relevant input box.

function Check() {
    if (document.forms["bookform"].room1.checked) {
        document.forms["bookform"].thisRoom1.value = "<?php echo($row_rsRoomCost['room1']; ?>";
    } else if (document.forms["bookform"].room2.checked) {
        document.forms["bookform"].thisRoom2.value = "<?php echo($row_rsRoomCost['room2']; ?>";
    } else if (document.forms["bookform"].room3.checked) {
        document.forms["bookform"].thisRoom3.value = "<?php echo($row_rsRoomCost['room3']; ?>";
    } 
}

输出的输入框是:

Room 1: <input type="text" name="thisRoom1" value="">
Room 2: <input type="text" name="thisRoom2" value="">
Room 3: <input type="text" name="thisRoom3" value="">

如您所见,我正在尝试使用php来填充数据库表中的相关值.但是,这当然只显示成本表中第一个记录的成本,而不管选中哪个房间.

As you see, I'm trying to use php to fill in the relevant value from the database table. However, this, of course, only shows the cost from the first record in the costs table regardless of which room is checked.

如何从表格中将所选房间的费用输入表格中正确的输入框中?

How do I get the cost of the chosen room from the table into the correct input box on the form?

我已经尝试过<?php echo($ row_rsRoomCost ['room1'])其中($ row_rsRoomCost ['costID'])='1';?> ,但这不起作用.我曾考虑过案例"陈述,但不知道该如何运作.我能想到的唯一方法是每个房间都有单独的SQL语句.例如: SELECT * FROM roomcost WHERE costID = 1

I've tried <?php echo($row_rsRoomCost['room1']) where ($row_rsRoomCost['costID']) = '1'; ?> but this doesn't work. I thought about 'case' statements but don't know how that would work. The only way I can think of is a seperate SQL statement for each room. eg: SELECT * FROM roomcost WHERE costID = 1

如何从表格中将选定房间的费用放入表格的正确输入框中?

How do I get the cost of the selected room from the table into the correct input box on the form?

推荐答案

遍历您的代码,我发现这将是解决问题的长途之路.

Going through your code I find that that would be the long way round of solving it .

  • 解决此问题的第一步是将数据放入可重用的前端源(如JSON)中(使用起来更容易).

示例:(结果在控制台日志F12中)

Example: (Results are in the console log F12)

                <?php

            $servername = "localhost";
            $username = "root";
            $password = "jono23";
            $dbname = "helpothers";

            // Create connection
            $conn = new mysqli($servername, $username, $password, $dbname);
            // Check connection
            if ($conn->connect_error) {
                    die("Connection failed: " . $conn->connect_error);
            }

            $sql = "SELECT * FROM `roomcost`";
            $result = $conn->query($sql);

            if ($result->num_rows > 0) {
                    // output data of each row
                    while($row = $result->fetch_assoc()) {
                            // echo "id: " . $row["costID"]. " - Name: " . $row["room"]. " " .$row["cost"]. "<br>";


                            // data you want to send to json
                            $data[] = array(
                                    'id' => $row['costID'],
                                    'room' => $row['room'],
                                    'cost' => $row['cost']
                            );

                            //}

                    }
            } else {
                    echo "0 results";
            }
            $conn->close();



            $json_data = json_encode($data);


            //print_r($json_data);






            ?>

            <!DOCTYPE html>
            <html lang="en" dir="ltr">
            <head>
                    <meta charset="utf-8">
                    <title></title>
            </head>
            <body>
                    <form id='bookform' >
                            <input type="checkbox" name="room1" value="room1" onClick="Check()">Room 1</input>
                            <input type="text" name="room1value"  readonly><br>
                            <input type="checkbox" name="room2" value="room2" onClick="Check()">Room 2</input>
                            <input type="text" name="room2value"  readonly><br>
                            <input type="checkbox" name="room3" value="room3" onClick="Check()">Room 3</input>
                            <input type="text" name="room3value" readonly><br>
                    </form >
                    <script type="text/javascript">
                    var Rooms = JSON.parse('<?php print_r($json_data) ; ?>');

                    console.log(Rooms);


                    function Check() {

                            //room1
                            if (document.forms["bookform"].room1.checked)
                            {
                                    document.forms["bookform"].room1value.value = Rooms[0].cost;
                                    console.log(Rooms[0].cost);
                            }else{
                                    document.forms["bookform"].room1value.value ='';
                            }

                            //room2
                            if (document.forms["bookform"].room2.checked)
                            {
                                    document.forms["bookform"].room2value.value = Rooms[1].cost;
                                    console.log(Rooms[1].cost);
                            }else{
                                    document.forms["bookform"].room2value.value ='';
                            }


                            //room3
                            if (document.forms["bookform"].room3.checked)
                            {
                                    document.forms["bookform"].room3value.value = Rooms[2].cost;
                                    console.log(Rooms[2].cost);
                            }else{
                                    document.forms["bookform"].room3value.value ='';
                            }
                    }



                    </script>

            </body>
            </html>

  • 首先,通过将SQL查询结果编码为json数组,您可以关闭数据库连接,以免耗尽不必要的资源在多个请求上

    • By encoding the SQL query results into a json array first you able to close the database connection so not to use up unnecessary resources on multiple requests

      然后通过将PHP JSON对象调用到JavaScript中,您可以更轻松地将其应用于html和JavaScript需要

      Then By calling that PHP JSON Object into JavaScript you can more easily apply it to your html and JavaScript Needs

      将PHP数据转换为JSON并使用JavaScript进行解析帮助我们使用rest api的

      Converting PHP Data To JSON and parse with JavaScript Help us work with things like rest api's

      这是可以在多种语言中找到JSON实现的主要原因,因为它是一种在不同编码语言之间共享数据的简便方法

      This is the main reason why JSON implementation can be found in many languages as its an easy way to share data across different coding languages

      我对处理数据的另一建议是不要将值存储在复选框中.为此,创建另一个文本输入并将其存储在此处.例如

      Another suggestion that I would make for the handling of the data is not to store the values in a checkboxes . Create another text input for that purpose and store them there . e.g

      <input type='text' id='gethandle1'>
      <script>
      let box1 = document.getElementById('gethandle1');
      box1.value = Rooms[0].cost; 
      </script>
      

      希望这对您有所帮助.

      这篇关于将MYSQL表中的数据输出到HTML表单中,具体取决于用户选择的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆