如何在PHP上使用AJAX检索MySQL值?

如何在PHP上使用AJAX检索MySQL值?

问题描述:

Ok, this one is taking me some time now, I've read other topics and cannot seem to solve it.

I have a select populated with a PHP function article_search() that retrieves all article names from a the table article in my DB

<select id="article_select">
    <?php
        $article_group = article_search();
        foreach($article_group as $item) {
            echo "<option value=\"{$item["idArt"]}\">{$item["name"]}</option>";
        }
    ?>  
</select>

What I need is, when the user selects an article, an AJAX function search the field price from the table article in the database and puts the result in this element:

<p>Price:
    <input type="text" class="details" id="price" name="price">
</p>

Needless to say that I have no experience in AJAX, but it seems like the only solution at these point.

Every bit of help would be appreciated.

好的,这个现在花了我一些时间,我已经阅读了其他主题,似乎无法解决它。 p>

我有一个填充了PHP函数的选项 article_search() strong>,它从我的数据库中的表文章 strong>中检索所有文章名称 p>

 &lt; select id =“article_select”&gt; 
&lt;?php 
 $ article_group = article_search(); 
 foreach($ article_group as $ item){  
 echo“&lt; option value = \”{$ item [“idArt”]} \“&gt; {$ item [”name“]}&lt; / option&gt;”; 
} 
?&gt;  
&lt; / select&gt; 
  code>  pre> 
 
 

我需要的是,当用户选择文章时,AJAX功能会搜索字段价格 strong> 数据库中的表文章 strong>并将结果放在此元素中: p>

 &lt; p&gt; Price:
&lt; input type =“text  “class =”details“id =”price“name =”price“&gt; 
&lt; / p&gt; 
  code>  pre> 
 
 

毋庸置疑,我没有经验 AJAX,但它似乎是这一点上唯一的解决方案。 p>

我们将不胜感激。 p> div>

Personally, I would put the price in the the original options:

<select id="article_select">
    <?php
        $article_group = article_search();
        foreach($article_group as $item) {
            echo "<option value=\"{$item["idArt"]}\" price=\"{$item['price']}\">{$item["name"]}</option>";
        }
    ?>  
</select>

Then, you can collect this using JQuery like so (http://jsfiddle.net/Twisty/6unsdztu/):

$(document).ready(function(){
    $("#article_select").change(function(){
        var price = $(this).find("option:selected").attr("price");
        var $inp = $('<input />',{
            type: "text",
            class: "details",
            id: "price_" + $(this).val(),
            name: "price",
            value: price
        });
        var $p = $('<p />');
        $p.append("<label>Price:</label>", $inp);
        $p.appendTo("#price_form");
    });
});

This seems like a bad idea overall. The user could try to manipulate the price if you're passing it back to the Database, unless they get a chance to negotiate the price.

Since the Price is in the DB, why bring it out to a text field? he end, if this is a shopping cart, we just need to know which items are in the cart, and we can calculate a total later or as we go. Hopefully the above example fits what you need. If not, comment or edit your post with more details.

I would suggest you have a look at some Ajax tutorials first. But basically what you need to do is (requires Jquery):

$(document).ready(function(){
    //if the user selects another option from the select element
    $("#article_select").change(function(){
        data = "function=updatePrice&value="+$(this).val();
        loadAjax(data);
    });
})

//sends the data to the server. In the example above you can use the two
//variables 'function' and 'value' as normal post parameters. 
function loadAjax (data) {

        req = $.ajax({
                type: 'POST',
                encoding:"UTF-8",
                url: 'index.php',
                cache: false,
                data: data,
                error: function (xhr, ajaxOptions, thrownError) {
                        alert("Error: "+thrownError);
                },
                xhr: function () {
                        var xhr = new window.XMLHttpRequest();
                        return xhr;
                },
                beforeSend: function () {

                },
                complete: function () {
                },
                success: function (response) {
                   response = $.parseJSON(response);
                   $("#price").val(response.price);
                }
        });
}

In your php code you can use the post variables and write a function like

if($_POST['function']=='updatePrice')
{
    $price = $model -> getPrice($_POST['value'])
}

which gets the price from your database. You could then for example assign the price to a variable. E.g.

$content['price'] = $priceFromDatabase;

afterwards you have to json_encode this variable with

 return json_encode($this -> content);

Of course you should do some sanitizing before using the post variables to prevent SQL injection etc.

However I would normally also do it the way @Twisty suggested to prevent unnecessary load for your server. But if you wanna learn Ajax in general, this would be the way to do it.

Hope that helps