选择下拉菜单时,使用数据库

时间:2016-02-20 13:37:49

标签: php ajax

我的代码有问题。我正在尝试使用数据库中的数据填充textbox。它需要在dropdownmenu中显示所选项目的价格。但它没有用。我可以填写dropdownmenu,但当我选择其中的某个项目时,我的textbox会保持空白。

我使用的是以下表结构:

forms (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `sort` int(1) NOT NULL,
  `name` varchar(100) NOT NULL,
  `price` decimal(7,2) NOT NULL,
  `tax` int(2) NOT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB  DEFAULT CHARSET=latin1 AUTO_INCREMENT=4 ;

// index.php

<?php
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "database";

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

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

if ($result->num_rows > 0) {
     echo "<select class='form-control select2' id='product1' name='product1' onChange='getstate(this.value);' style='width: 100%;'>";
     echo "<option selected disabled hidden value=''></option>";
     // output data of each row
     while($row = $result->fetch_assoc()) {
                      echo "<option value='" . $row["id"]. "'>" . $row["name"]. "</option>";
     }                   
echo "</select>";
} else {
     echo "0 results";
}

$conn->close();

?>
<html>

<!-- Your text input -->
<input id="product_name" type="text">

</html>

<script>
function getPrice() {

    // getting the selected id in combo
    var selectedItem = jQuery('.select2 option:selected').val();

    // Do an Ajax request to retrieve the product price
    jQuery.ajax({
        url: 'get.php',
        method: 'POST',
        data: 'id=' + selectedItem,
        success: function(response){
            // and put the price in text field
            jQuery('#product_name').val(response);  
        },
        error: function (request, status, error) {
            alert(request.responseText);
        },
    });
}
</script>

get.php

<?php
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "database";

// Create connection
$conn = new mysqli($servername, $username, $password, $dbname) ;
// Check connection
if ($conn->connect_error) 
    {
    die('Connection failed: ' . $conn->connect_error) ;
    } 
else 
    {
    $product1 = filter_input(INPUT_POST, 'id', FILTER_SANITIZE_NUMBER_INT) ;

    $query = 'SELECT price FROM forms WHERE id=" . $product1 . " ' ;

    $res = mysqli_query($conn, $query) ;
    if (mysqli_num_rows($res) > 0) 
    {
    $result = mysqli_fetch_assoc($res) ;
            echo json_encode($result['price']);

    }
    else
        {
        echo json_encode('no results') ;
        }

    }
?>

有人可以帮我解决这个问题吗?

1 个答案:

答案 0 :(得分:0)

<?php
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "database;

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

    $query = 'SELECT price FROM forms WHERE id=' . $product1;

    $res = mysql_query($query);
    if (mysql_num_rows($res) > 0) {
        $result = mysql_fecth_assoc($res);

       echo json_encode($result['price']);


}
?>

每当你发送和接收数据时,它应该是AJSON编码的AJAX来读取你的数据,所以die不会工作,因为它是一个异步事件,你应该在客户端使用json_encode。

jQuery.ajax({
    url: 'get.php',
    method: 'POST',
    data: 'id=' + selectedItem,
    success: function(response){
        // and put the price in text field
        jQuery('#product_name').val(response);  
    },
    error: function (request, status, error) {
        alert(request.responseText);
    },
}); 

现在响应应该有效,对于像键和值这样的大数据,您应该转储响应console.log(response)并检查obj键值最佳实践