我怎样才能在mysql查询中使用jquery变量

时间:2017-04-22 10:00:12

标签: javascript php jquery

目前,我正在使用$ _GET来查询mysql并填充select语句,该语句正常。但是,我现在需要使用jquery变量查询db,并且无法找到使用' depts'而不是' $ _ GET [' dept']'。

我已经声明了var global,但意识到你不能在查询中使用var。

如果有人能告诉我如何修改我的代码来实现这一目标,我将不胜感激。感谢

php代码填充选择

<?php
    $conn = mysql_connect("localhost", "root", "");
    mysql_select_db("sample", $conn);
    $result = mysql_query("SELECT * FROM boxes where department = '{$_GET['dept']}' and status = 1 ORDER BY custref ASC");
?>

    <select name="boxdest[]" id="boxdest" size="7" multiple="multiple">

<?php
    $i=0;
    while($row = mysql_fetch_array($result)) {
    ?>
    <option value="<?php echo $row["custref"];?>"><?php echo $row["custref"];?></option>
    <?php
    $i++;
    }
?>

    </select>

jQuery更改事件代码

<script type="text/javascript">

    var depts;

    $('#dept').on('change', function() {

    depts = $('#dept option:selected').html();

    if (depts === 'Select a Department') {

       $('#deptResult').html('<p>ERROR: You must Select a department to proceed<p/>').css({'color':'red'});
       $( "#submit" ).prop( "disabled", true );
       return;
    }
      $('#deptResult').html('<p>SUCCESS: You have selected the following dept: ' + depts + '</p>').css({'color':'black'});
    });
</script>

2 个答案:

答案 0 :(得分:2)

使用jquery ajax(),如:

$.ajax({
    url     : 'process.php',
    method  : 'get',
    async   : false,
    data    : {
        variable : value,  
        // you can pass multiple variables like this and this is available in php like $_REQUEST['variable']
    },
    success : function(response){
        // do what ever you want with the server resposne
    }
});

process.php:

$variable = $_REQUEST['variable'];  // you can use $variable in mysql query

答案 1 :(得分:1)

你能吗?的

您必须使用AJAX。我可以为这项任务推荐简单的API。使用JSON的示例:

api.php

<?php

function output($arr) {
    echo json_encode($arr);
    exit();
}

if (!isset($_GET['dept'])) {
    output([
        'success' => false,
        "message" => "Department not defined"
    ]);
}

$mysqli = new mysqli("localhost", "root", "", "test");
if ($mysqli->connect_errno) {
    output([
        'success' => false,
        'dept' => $_GET['dept'],
        'message' => "Connect failed: ". $mysqli->connect_error
    ]);
}

$result = $mysqli->query("SELECT DISTINCT(`department`) FROM `boxes`");
if (!$result) {
    output([
        'success' => false,
        'dept' => $_GET['dept'],
        'message' => "Query failed"
    ]);
}

$departments = [];
while($row = $result->fetch_array(MYSQLI_ASSOC)) {
    $departments[] = $row['department'];
}

if (!in_array($_GET['dept'], $departments)) {
    output([
        'success' => false,
        'dept' => $_GET['dept'],
        'message' => "Department not present in database"
    ]);
}

$result = $mysqli->query("SELECT `custref` FROM `boxes` WHERE `department`='". $_GET['dept'] ."' ORDER BY `custref` ASC");
if (!$result) {
    output([
        'success' => false,
        'dept' => $_GET['dept'],
        'message' => "Query failed"
    ]);
}

$custref = [];
while($row = $result->fetch_array(MYSQLI_ASSOC)) {
    $custref[] = $row['custref'];
}
output([
    'success' => true,
    'dept' => $_GET['dept'],
    'custref' => $custref
]);

$result->free();
$mysqli->close();

$(function () {
    $('select[data-key][data-value]').each(function (i, element) {
        var key = $(element).data("key");
        var value = $(element).data("value");
        var $originSelector = $('[name="'+ key +'"]');

        /**
         * Get options from element by name
         */
        function getOptions () {
            var request = {};
            request[key] = $originSelector.val();
            $.ajax({
                url: "./api.php",
                method: "GET",
                dataType: "json",
                data: request
            }).done(function(data) {
                setOptions(data);
            });
        }
        
        /**
         * Remove old options
         */
        function clearOptions () {
            $(element).find('option').remove();
        }
        
        /**
         * Put new options in input
         */
        function setOptions (data) {
            if (data['success'] && data[value] !== undefined) {
                clearOptions();
                $.each(data[value], function (i, option) {
                    $(element).append('<option value="'+ option +'">'+ option +'</option>');
                });
            }
        }

        getOptions();
        $originSelector.on("change", function () {
            getOptions();
        });
    });
});
<select name="dept">
    <option value="accounting">Accounting</option>
    <option value="it">Information technology</option>
</select>

<select name="boxdest[]" id="boxdest" size="7" multiple="multiple" data-key="dept" data-value="custref"></select>

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>