检索数据mysql php

时间:2017-03-25 18:26:43

标签: php jquery mysql

我有两个搜索框的实时搜索,从mysql数据库中获取数据。当我按下提交按钮时,我想显示用户输入的数据库中的行数据。我的问题是它从查询输出不同的值,但只从第二个搜索框中输出,我找不到原因。

这是我的代码:

jQuery的:

$(document).ready(function(){
    $('#button').on('click', function(){
        var smartphone1 = $('#smartphone1').val();
        var smartphone2 = $('#smartphone2').val();
        if ($.trim(smartphone1) != '' && $.trim(smartphone2) != ''){
            $.post('fetchdata.php', {smartphone1: smartphone1, smartphone2: smartphone2}, function(data){
                $('#namedata').text(data);
            });
        }
    });  
});

PHP:

if (isset($_POST['smartphone1']) AND isset($_POST['smartphone2'])) {
    if (empty($_POST['smartphone1']) AND empty($_POST['smartphone2'])) {
        exit();
    }

    $recherche = filter_input(INPUT_POST, 'smartphone1', FILTER_SANITIZE_STRING);
    $recherche = filter_var($recherche, FILTER_SANITIZE_SPECIAL_CHARS);

    $search = filter_input(INPUT_POST, 'smartphone2', FILTER_SANITIZE_STRING);
    $search = filter_var($search, FILTER_SANITIZE_SPECIAL_CHARS);

    require "databasecon.php";

    $mysqli = new mysqli($host_name, $user_name, $password, $database);

    if (!$stmt = $mysqli->prepare("SELECT name , capacityingo , ram , prix , photoquality FROM smartphone WHERE name = ?")) {

        $error = array
            (
                'error' => 'The statement could not be prepared'
            );

        echo json_encode($error);
        exit();
    }

    $stmt->bind_param('s', $recherche);
    $stmt->bind_param('s', $search);

    if (!$stmt->execute()) {
        $error = array
            (
                'error' => 'The statement could not be executed'
            );

        echo json_encode($error);
        exit();
    }

    $res = $stmt->get_result();
    $datasmartphone1 = array();
    $datasmartphone2 = array();
    while ($row = $res->fetch_assoc())
    {
        //add each result to an array
        $datasmartphone1[] = $row;
        $datasmartphone2[] = $row;
    }
    //print the array encoded in JSON
    echo json_encode($datasmartphone1);
    echo json_encode($datasmartphone2);    
}

感谢您的帮助。

1 个答案:

答案 0 :(得分:0)

您的查询字符串只有一个参数,您可以使用第一个过滤器替换,然后使用第二个过滤器替换。

"SELECT name, capacityingo, ram, prix, photoquality FROM smartphone WHERE name = ?"

$stmt->bind_param('s', $recherche);
$stmt->bind_param('s', $search);

我认为你应该把它改成

"SELECT name, capacityingo, ram, prix, photoquality FROM smartphone WHERE name = ? OR name = ?"

或者您想要使用

的第二个搜索框值的任何内容