在将数据输入文本区域时搜索数据库

时间:2015-01-12 10:17:24

标签: javascript php ajax

我有一个表数据[列:id,问题,答案每个问题都有答案];在前端/ UI中,我有一个textarea,而我将一个问题粘贴到此字段,在db中搜索确切的问题并显示结果。 我想ajax无需点击任何搜索按钮。当我将问题粘贴到文本区域时,我想要这个。

我正在使用的代码

HTML:

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="utf-8">       
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title>CSS3</title>
    <!-- Latest compiled and minified CSS -->
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.1/css/bootstrap.min.css">
<!-- Latest compiled and minified JavaScript -->
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.1/js/bootstrap.min.js"></script>
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
  </head>
      <body>
        <div class="container">
          <div class="jumbotron">
            <h1>PHP5</h1>
    <form class="form-inline">
      <div class="form-group">

         <input size="100" type="text" id="searchid"  class="form-control" rows="10" cols="100" />
      </div>

     <div id="resultdiv"></div>
    </form>
          </div>
        </div> <!-- /container -->
        <!-- IE10 viewport hack for Surface/desktop Windows 8 bug -->
      </body>
    </html>

jQuery的:

<script type="text/javascript">
        $(document).ready(function() {

            $('#searchid').keydown(function (e){ // Event for enter keydown.

            if(e.keyCode == 13){

            var idvalue = $("#searchid").val(); // Input value.

                $.ajax({ //Ajax call.

                    type: "GET",
                    url: "search.php",
                    data: 'id=' + idvalue , 
                    type: 'json',
                    success: function(msg){
                        // Show results in textareas.
                        msg = JSON.parse( msg );  // Line added 

                        alert (msg);

                         $('#resultdiv').val(msg.answer);

                        }

                    }); // Ajax Call
                } //If statement

        }); //document.ready
    </script>

我的Search.php

      <?php

     if ($_GET['id']):   

        $dataid = json_decode($_GET['id']);


        // Connect to database.
        $con = mysqli_connect("localhost","root",""); 
        mysqli_select_db ($con,'exam_css3'); 

        // Get the values from the table.
        $sql = "SELECT answer FROM exam_css3 where question LIKE '$dataid' ";
        $result = mysqli_query($con,$sql);

        while($row = mysqli_fetch_assoc($result)) 
        {   
        $answer = $row[answer]; 

        }

    $rows = array('answer' => $answer); 

    echo json_encode($rows);

    endif;

    ?>

此代码无效,任何人都可以提供帮助吗?

2 个答案:

答案 0 :(得分:1)

除了其他方面,PHP中存在一些问题。

首先,您搜索$dataid,这意味着完全匹配。你需要做

"SELECT answer FROM exam_css3 where question LIKE '%{$dataid}' ";

然后你总是只保存一个答案,并且你没有在'answer'周围指定引号,这可能会导致PHP警告,这会破坏JSON输出:

    while($row = mysqli_fetch_assoc($result)) 
    {   
        $answer = $row[answer]; 
    }
    $rows = array('answer' => $answer); 

   echo json_encode($rows);

endif;

所以你可能想把它重写为

<?php

if (array_key_exists('id', $_GET)) {

    $dataid = json_decode($_GET['id']);
    // Here it would be good to check whether the decoding succeeded.
    // I'd also try doing in HTML:   data: { id: idvalue }

    // Connect to database.
    $con = mysqli_connect("localhost", "root", ""); 
    mysqli_select_db ($con,'exam_css3'); 

    // Get the values from the table.
    // Only interested in one match.
    $sql = "SELECT answer FROM exam_css3 where question LIKE '%{$dataid}%' LIMIT 1";
    $result = mysqli_query($con,$sql);

    $answer = mysqli_fetch_assoc($result);
    if (null === $answer) {
        $answer = array('answer' => 'nothing found', 'status' => 'error');
    }

    // Since we're putting this into HTML...
    $answer['answer'] = HTMLspecialChars($answer['answer']);

} else {
    $answer = array('answer' => 'no query was supplied', 'status' => 'error');
}
Header ('Content-Type: application/json');
die(json_encode($answer));

在上面的代码中,我添加了一个'status'变量,以便在jQuery中可以执行

if (msg.error) {
    alert("Error: " + msg.answer);
    return;
}

进一步区分正确答案和错误答案。

存在其他问题(例如,您应该使用PDO并切换到准备好的查询;如果问题包含引号,例如

What's a SQL injection?

您的SQL搜索会抛出错误。 这不仅限于SQL注入没有包含引号的查询将起作用。在将其放入查询之前,您至少需要escape the string dataid。

答案 1 :(得分:0)

您在ajax中定义了两倍typejson dataType不是简单的typetype是get,你不需要设置,这是默认值。

第二个问题是,您将数据作为字符串传递,而不是作为json对象传递,因此在服务器端,这将是一个数组,您不能json_decode