【问题标题】:Fetch value from Database and fill all textbox if dropdown value change如果下拉值更改,则从数据库中获取值并填充所有文本框
【发布时间】:2018-07-08 21:30:25
【问题描述】:

我正在尝试根据下拉值选择填充所有文本框值。而且我还通过 SQL 查询填充下拉值。这是 HTML 代码:

<select name="name" ID="name" class="form-control">
<option value="Select">Select</option>
<?php
$qu="Select DISTINCT Cname from Client_table";
$res=mysqli_query($con,$qu);
while($r=mysqli_fetch_row($res))
{ 
    echo "<option value='$r[0]'> $r[0] </option>";
                                            
}
?> 
</select>
<label>Address</label><input type="text" name="add"/>
<label>Contact</label><input type="text" name="con"/>

数据库:

  Client_table
   C_no             Cname           Caddress          Ccontact
    1               Mohit             xyz             0123645789
    2               Ramesh            abc             7485962110

在这里我很困惑如何根据下拉选择查找客户的地址和联系方式并用此值填充文本框

【问题讨论】:

  • 表中同名的客户多吗?
  • 例如:如果Mohit在表中有两条记录,那么他有两个不同的地址,或者两个不同的联系电话。每条记录一个。那么创建DISTINCT 是错误的,因为这样您只会将一个地址(或联系电话)获取到您的组合框中...
  • 不是现在,但可能在将来。目前我的表中只有 1 条记录

标签: javascript php html sql


【解决方案1】:

将查询更改为

Select DISTINCT Cname,Caddress,Ccontact from Client_table

并更改以下语句

echo "<option value='$r[0]'> $r[0] </option>";

echo '<option data-add="'.$r[1].'" data-con="'.$r[2].'" value='.$r[0].'> '.$r[0].' </option>';

修改选择为

<select name="name" ID="name" class="form-control" onchange="myFunction()"> 

添加以下javascript

function myFunction(){
 var index = document.getElementById("name").selectedIndex;
    var add = document.getElementById("name").options[index].getAttribute("data-add");
var con = document.getElementById("con").options[index].getAttribute("data-con");
document.getElementsByName("add")[0].value = add;
document.getElementsByName("con")[0].value = con;
}

JsFiddle Code

【讨论】:

  • 您是否添加了 **onchange="myFunction()" 以相应地选择并更改查询和回显语句>因为我尝试过它的工作原理。
  • 是的,我改变了
  • 检查这个Jsfiddle 它正在工作
【解决方案2】:

一点说明:当您第一次访问页面 (index.php) 时,数据被加载到组合框中。每个option 标记接收客户端编号作为值(C_no)和其他详细信息,作为文本。

另一方面,当您在组合框中选择一个值时,您需要从数据库中获取额外的客户端数据。为此,您需要 jquery 和 ajax。有了它,当组合框的值改变时,你必须向服务器发出一个ajax请求(getClient.php)。作为响应,它会向您发送数据库表中的相应数据。然后,您获取数据并将其放在您喜欢的任何位置 - 在本例中是输入。

一点建议:我建议您开始使用准备好的语句 - 以避免 sql 注入 - 并且不要将用于从 db 获取数据的 php 代码与 html 代码混合。把它们分开。首先,在页面顶部获取数据并将其保存到数组中。然后,在 html 代码中,只使用数组来遍历获取的数据。


index.php

<?php
require 'connection.php';

$sql = 'SELECT C_no, Cname, Caddress FROM Client_table ORDER BY Cname ASC';

// Prepare the statement.
$statement = mysqli_prepare($connection, $sql);

// Execute the statement.
mysqli_stmt_execute($statement);

// Get the result set from the prepared statement.
$result = mysqli_stmt_get_result($statement);

// Fetch the data and save it into an array for later use.
$clients = mysqli_fetch_all($result, MYSQLI_ASSOC);

// Free the memory associated with the result.
mysqli_free_result($result);

// Close the prepared statement. It also deallocates the statement handle.
mysqli_stmt_close($statement);
?>

<!DOCTYPE html>
<html>
    <head>
        <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1" />
        <meta name="viewport" content="width=device-width, initial-scale=1, user-scalable=yes" />
        <meta charset="UTF-8" />
        <!-- The above 3 meta tags must come first in the head -->

        <title>Demo</title>

        <script src="https://code.jquery.com/jquery-3.2.1.min.js" type="text/javascript"></script>

        <script type="text/javascript">
            $(document).ready(function () {
                $('#name').change(function (event) {
                    var cNo = $(this).val();

                    if (cNo === 'Select') {
                        $('#address').val('');
                        $('#contact').val('');
                    } else {
                        $.ajax({
                            method: 'post',
                            dataType: 'json',
                            url: 'getClient.php',
                            data: {
                                'cNo': cNo
                            },
                            success: function (response, textStatus, jqXHR) {
                                if (!response) {
                                    alert('No client data found.');
                                } else {
                                    $('#address').val(response.address);
                                    $('#contact').val(response.contact);
                                }
                            },
                            error: function (jqXHR, textStatus, errorThrown) {
                                alert('An error occurred. Please try again.');
                            },
                            cmplete: function (jqXHR, textStatus) {
                                //...
                            }
                        });
                    }
                });
            });
        </script>

        <style type="text/css">
            body {
                padding: 30px;
            }

            input, select {
                display: block;
                margin-bottom: 10px;
            }
        </style>
    </head>
    <body>

        <div class="container">
            <select name="name" id="name" class="form-control">
                <option value="Select">- Select -</option>
                <?php
                foreach ($clients as $client) {
                    ?>
                    <option value="<?php echo $client['C_no']; ?>">
                        <?php echo $client['Cname'] . ' (' . $client['Caddress'] . ')'; ?>
                    </option>
                    <?php
                }
                ?> 
            </select>

            <label>Address</label>
            <input type="text" id="address" name="address"/>

            <label>Contact</label>
            <input type="text" id="contact" name="contact"/>
        </div>

    </body>
</html>

getClient.php

<?php

require 'connection.php';

// Validate posted value.
if (!isset($_POST['cNo']) || empty($_POST['cNo'])) {
    echo json_encode(FALSE);
    exit();
}

$cNo = $_POST['cNo'];

$sql = 'SELECT 
            Caddress AS address,
            Ccontact AS contact
        FROM Client_table 
        WHERE C_no = ? 
        LIMIT 1';

// Prepare the statement.
$statement = mysqli_prepare($connection, $sql);

/*
 * Bind variables for the parameter markers (?) in the 
 * SQL statement that was passed to prepare(). The first 
 * argument of bind_param() is a string that contains one 
 * or more characters which specify the types for the 
 * corresponding bind variables.
 * 
 * @link http://php.net/manual/en/mysqli-stmt.bind-param.php
 */
mysqli_stmt_bind_param($statement, 'i', $cNo);

// Execute the statement.
mysqli_stmt_execute($statement);

// Get the result set from the prepared statement.
$result = mysqli_stmt_get_result($statement);

// Fetch the data and save it into an array for later use.
$clientDetails = mysqli_fetch_array($result, MYSQLI_ASSOC);

// Free the memory associated with the result.
mysqli_free_result($result);

// Close the prepared statement. It also deallocates the statement handle.
mysqli_stmt_close($statement);

if (!isset($clientDetails) || !$clientDetails) {
    echo json_encode(FALSE);
} else {
    echo json_encode($clientDetails);
}

exit();

connection.php

<?php 

// Db configs.
define('HOST', 'localhost');
define('PORT', 3306);
define('DATABASE', 'your-db');
define('USERNAME', 'your-user');
define('PASSWORD', 'your-pass');

// Display eventual errors.
error_reporting(E_ALL);
ini_set('display_errors', 1); /* SET IT TO 0 ON A LIVE SERVER! */

// Enable internal report functions.
$mysqliDriver = new mysqli_driver();
$mysqliDriver->report_mode = (MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);

// Create db connection.
$connection = mysqli_connect(HOST, USERNAME, PASSWORD, DATABASE, PORT);

创建表语法

DROP TABLE IF EXISTS `Client_table`;

CREATE TABLE `Client_table` (
  `C_no` int(11) unsigned NOT NULL AUTO_INCREMENT,
  `Cname` varchar(100) DEFAULT NULL,
  `Caddress` varchar(100) DEFAULT NULL,
  `Ccontact` varchar(100) DEFAULT NULL,
  PRIMARY KEY (`C_no`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

INSERT INTO `Client_table` (`C_no`, `Cname`, `Caddress`, `Ccontact`)
VALUES
    (1,'Mohit','xyz','0123645789'),
    (2,'Ramesh','abc','7485962110'),
    (5,'Tanja','def','1232347589'),
    (6,'Paul','pqr','0797565454'),
    (7,'Mohit','klm','0123645789');

【讨论】:

    【解决方案3】:
    <?php
    $servername = "localhost";
    $username = "root";
    $password = "";
    $dbname="stack";
    // Create connection
    mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
    $conn = new mysqli($servername, $username, $password, $dbname);
    
    
    $qu = "SELECT DISTINCT Cname,Caddress,Ccontact FROM Client_table";
    $res = $conn->query($qu);
    ?>
    <select name="name" ID="name" onchange="myFunction()" class="form-control">
    <option value="Select">Select</option>
    <?php
    
    while($r = mysqli_fetch_row($res))
    { 
        echo "<option data-add='$r[1]'  data-con='$r[2]'  value='$r[0]'> $r[0] </option>";
    }
    ?> 
    </select>
    <label>Address</label><input type="text" name="add" id="add"/>
    <label>Contact</label><input type="text" name="con" id="con"/>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
    <script>
    
    
        function myFunction(){
            var address = $('#name').find(':selected').data('add');
            var contact = $('#name').find(':selected').data('con');
            $('#add').val(address);
            $('#con').val(contact);
        }
    </script>
    

    【讨论】:

    • 是的,它现在正在工作。但是请你告诉我它是否适用于同名客户。
    • 是的,它适用于同名客户。如果您遇到任何问题,您可以通知我。谢谢
    【解决方案4】:

    JavaScript 文件:

     function getdata(str) {
    
     if (str == "")
    
     {
    
         document.getElementById("no_of_sms").value = "";
         document.getElementById("no_of_days").value = "";
         document.getElementById("descr").value = "";
         document.getElementById("state-pkg").value = "";
         document.getElementById("price-pkg").value = "";
    
         return;
    
    }
    
    if (window.XMLHttpRequest) 
    
    { 
    
        xmlhttp = new XMLHttpRequest();
    
    } 
    else
    {
    
        xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
    }
    xmlhttp.onreadystatechange=function() {
    if (this.readyState==4 && this.status==200) {
            var data = xmlhttp.responseText.split("#");
            var db_no_of_sms = decodeURIComponent(data[0]);
            var db_no_of_days = decodeURIComponent(data[1]);
            var db_f_state = decodeURIComponent(data[2]);
            var db_f_price = decodeURIComponent(data[3]);
            var db_f_desc = decodeURIComponent(data[4]);
            document.getElementById("no_of_sms").value=db_no_of_sms;
            document.getElementById("no_of_days").value = db_no_of_days;
            document.getElementById("descr").value = db_f_desc;
            document.getElementById("state-pkg").value = db_f_state;
            document.getElementById("price-pkg").value = db_f_price;
    }
    
    
      }
    
    xmlhttp.open("GET","functions/getdata.php?q="+str,true);
    
    xmlhttp.send();
    
    }
    

    PHP 文件:

    <?php
            $q = $_GET['q'];
             $host="localhost";
              $db_username="root";
              $db_password=""; 
    
              $con = mysqli_connect("$host", "$db_username", "$db_password"); 
               if (!$con)
                 {
                die('Could not connect: ' . mysqli_error($con));
                  }
                 mysqli_select_db($con,"business_details");
                 $sql="SELECT * FROM packages where p_name = '$q'";
                $result = mysqli_query($con,$sql);
                 $row=mysqli_fetch_assoc($result);
               $db_no_of_sms = $row['no_of_sms'];
              $db_no_of_days = $row['days'];
             $db_f_state = $row['state'];
              $db_f_price = $row['price'];
            $db_f_desc = $row['description'];
             echo 
         $db_no_of_sms."#".$db_no_of_days."#".$db_f_state."#".$db_f_price."#".$db_f_desc;
    
        ?>
    

    【讨论】:

      【解决方案5】:
        type: "GET",
        dataType: "json",                      
        success: function(data) {
            console.log(data[0]['qty']);
      
            $.each(data, function(key, value) {
                $('#qty').val(data[0]['qty']);
            });
        }
      });
      

      【讨论】:

      • 请在您的答案中添加一些解释,以便其他人可以从中学习
      • 虽然此代码可能会解决问题,including an explanation 关于如何以及为什么解决问题将真正有助于提高您的帖子质量,并可能导致更多的赞成票。请记住,您正在为将来的读者回答问题,而不仅仅是现在提问的人。请edit您的回答添加解释并说明适用的限制和假设。
      猜你喜欢
      • 2017-09-26
      • 2018-12-13
      • 2023-03-29
      • 2019-04-09
      • 2014-01-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多