如何将主键ID而不是属性值传递到数据库中

时间:2015-11-19 09:12:33

标签: javascript php html mysql

我有一个输入框,用户输入邮政编码。我创建了一个自动建议功能,根据我在数据库中存储的邮政编码推荐邮政编码。现在我把它链接到邮政编码的实际价值而不是主键。我不知道如何将主键传递给我的PHP文件而不是实际值。

HTML:

<div class="label">Zip Code:</div><br>
    <input type="text" id = "zip_id" class="tftextinput2" autocomplete = "off" name="zip" placeholder="Please enter your Zip Code" onkeyup = "autocomplete()">
    <ul id = "zip_codes_list_id"></ul>

JS:

function autocomplete() 
{
    var min_length = 1; 
    var keyword = $('#zip_id').val();
    if (keyword.length >= min_length) {
        $.ajax({
            url: 'ajax_refresh.php',
            type: 'POST',
            data: {keyword:keyword},
            success:function(data){
                $('#zip_codes_list_id').show();
                $('#zip_codes_list_id').html(data);
            }
        });
    } else {
        $('#zip_codes_list_id').hide();
    }
}
function set_item(item) 
{
    // change input value
    $('#zip_id').val(item);
    // hide proposition list
    $('#zip_codes_list_id').hide();
}

PHP:

<?php
    //connect to db here
    $keyword = '%'.$_POST['keyword'].'%';
    $sql = "SELECT * FROM zip_codes WHERE zip LIKE (:keyword) ORDER BY zip_codes_id ASC LIMIT 0, 10";
    $query = $pdo->prepare($sql);
    $query->bindParam(':keyword', $keyword, PDO::PARAM_STR);
    $query->execute();
    $list = $query->fetchAll();
    foreach ($list as $rs) 
    {
        // put in bold the written text
        $zip = str_replace($_POST['keyword'], '<b>'.$_POST['keyword'].'</b>', $rs['zip']);
        // add new option
        echo '<li onclick="set_item(\''.str_replace("'", "\'", $rs['zip']).'\')">'.$zip.'</li>';
    }
?>

从这里我可以在我的php文件中执行POST请求,我会存储用户输入的实际邮政编码。但是我想存储与该邮政编码相关联的主键。

1 个答案:

答案 0 :(得分:0)

试试这个:

foreach ($list as $rs) 
        {
            // put in bold the written text
            $zip = str_replace($_POST['keyword'], '<b>'.$_POST['keyword'].'</b>', $rs['zip']);
            // add new option
            echo '<li " onclick="set_item(\''.str_replace("'", "\'", $rs['primary_key_column_name']).'\')">'.$zip.'</li>';
        }