doxn43207 2018-04-26 04:58
浏览 180
已采纳

使用AJAX将SQL WHERE查询转换为javascript

I am trying to pass a javascript variable into an SQL WHERE query and I keep getting null in return.

On-click of a button, the buttonClick function is ran:

<script>
    var var1;
    function buttonClick(elem){
        var1 = elem.src              //this gets the url from the element
        var path = var1.slice(48);   //this cuts the url to img/art/9/1.jpg
        ajax = theAjax(path);
        ajax.done(processData);
        ajax.fail(function(){alert("Failure");});
    }

    function theAjax(path){
        return $.ajax({
            url: 'info.php',
            type: 'POST',
            data: {path: path},
        });
    }

    function processData(response_in){
        var response = JSON.parse(response_in);
        console.log(response);
    }
</script>

Here is the code stored in the info.php file:

<?php
    $path = $_POST['path'];

    $result3 = mysqli_query("SELECT itemName from images WHERE imgPath='$path'");
    $json = json_encode($result3);

    echo $json
?>

As you can see, once I click the button, the buttonClick() function is ran and a variable stores the image path or src. That path variable is send to theAjax() function where it is passed to the info.php page. In the info.php page, the SQL WHERE query is ran and returned to the processData() function to be parsed and printed in the developer console. The value printed shows null.

Below is a picture of what I am trying to get from the database: enter image description here

  • 写回答

3条回答 默认 最新

  • duanbei3747 2018-04-26 05:07
    关注

    1.Check that path is correct or not? you can check inside jquery using console.log(path); or at PHP end by using print_r($_POST['path']);

    2.Your Php code missed connection object as well as record fetching code.

    <?php
    
        if(isset($_POST['path'])){
            $path = $_POST['path'];
    
            $conn = mysqli_connect ('provide hostname here','provide username here','provide password here','provide dbname here') or die(mysqli_connect_error());
    
            $result3 = mysqli_query($conn,"SELECT itemName from images WHERE imgPath='$path'");
    
            $result = []; //create an array
    
            while($row = mysqli_fetch_assoc($result3)) {
                 $result[] = $row; //assign records to array
            }
            $json = json_encode($result); //encode response
            echo $json; //send response to ajax
        }
    
    ?>
    

    Note:- this PHP query code is wide-open for SQL INJECTION. So try to use prepared statements of mysqli_* Or PDO.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?