【问题标题】:Setting a select list from values in a database从数据库中的值设置选择列表
【发布时间】:2012-11-13 20:55:19
【问题描述】:

我有 2 个选择列表,一个命名产品,另一个用于数量。

<select name="fish" id="fish">
    <option value="blueFish">Blue Fish</option>
    <option value="redFish">Red Fish</option>
    <option value="pinkFish">Pink Fish</option>
    <option value="greenFish">Green Fish</option>
</select>

<select name="numFish" id="numFish">
    <option value="0">0</option>
    <option value="1">1</option>
    <option value="2">2</option>
    <option value="3">3</option>
    <option value="4">4</option>
    <option value="5">5</option>
   <option value="6">6</option>
</select>

I would like it so when a product is chosen, the corresponding quantity from the database will be set accordingly.

所以如果有记录说顾客比利买了5条粉红鱼,当我选择粉红鱼时,数量选择列表会变成5条。

这将用于使用 MySQL 数据库的 PHP 表单。

这样的功能是否可行,如果可以,我将如何去做?

【问题讨论】:

  • 不可能。你需要 Javascript。

标签: php html mysql sql forms


【解决方案1】:

您可能想在 google 上搜索 ajax 请求。它所做的是通过 javascript 检测更改(在您的情况下),将您选择的值发送到另一个 php 脚本,该脚本应该执行 sql 查询以返回数量。 ajax 请求将捕获返回的值,并通过 javascript 再次从选择下拉列表中更改值。

所有这些都会在后台发生,您的网站不会刷新。

如果你不是很习惯 javascript,你可以看看 jquery 框架,它使这项任务更容易一些,并且记录了很多示例。

我没有粘贴任何代码,因为假设您不熟悉 javascript/jquery/ajax。您可能想阅读一些文档并尝试一下,当您遇到具体问题时再回来,这将是 Stackoverflow 中的正常工作流程。

编辑:(OP要求的一些代码) Javascript:

$('#fish').change(function(){
    var fishType = $('#fish select option:selected');
    $.ajax("getQuantity.php", {fish: fishType}, function(data){
        data = JSON.parse(data);
        if(data.status == "OK"){
            var quantity = data.quantity;
            $('#numFish option[value='+quantity+']').prop("selected", true);
        } else {
            alert("error");// or console.log(), whatever you prefer
        }
    }
});

php (getQuantity.php):

<?php
    $fish = $_POST['fish']; //getting the fish type
    $sql = "your SQL to select the fish quantity for that type";
    $result = mysqli_query($mysqli, $sql);

    if(mysqli_num_rows($result)>0){
        $row = mysqli_fetch_assoc($result);
        $data = array("status" => "OK", "quantity" => $row['quantity']); // you can just output a string with the number if you want, but this way you have more control and better debugging.
        echo json_encode($data);
    }
?>

这是一个基本代码,它仍然需要为数据库捕获一些错误或返回不同的状态。但基本上就是这样。我什至没有测试该代码,因此仅将其用作指南。

【讨论】:

  • 我不精通 JavaScript,但我已经在我的网站上使用 jquery 来实现一些其他功能,因此欢迎提供示例代码 sn-p。
  • 在我的回答中添加了一个小例子
  • 请帮帮我:同样的问题:stackoverflow.com/questions/26916065/…
【解决方案2】:

&lt;select name="fish" id="fish"&gt; 更改为&lt;select name="fish" id="fish" onchange="getQuantity(this.value);"&gt;

在javascript中声明如下函数:

function getQuantity( o ) {
   // get the quantity from the database using ajax,
   // and set the quantity dropdown here.
}

【讨论】:

    猜你喜欢
    • 2016-07-03
    • 1970-01-01
    • 1970-01-01
    • 2012-09-13
    • 2017-10-21
    • 1970-01-01
    • 2012-09-30
    • 2017-05-26
    • 2015-04-14
    相关资源
    最近更新 更多