2017-03-25 37 views
-1

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

这里是我的代码:

的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);  
} 

谢谢您的帮助。

+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 = ?" 

或任何你想使用的第二搜索框值