2015-08-03 90 views
0

我嘗試在我的網站中包含實時搜索。 這是我的代碼:AJAX實時搜索JSON數組爲空

的index.html:

<script src="typeahead.min.js"></script> 
<input type="text" name="typeahead" class="typeahead tt-query" autocomplete="off" spellcheck="false" placeholder="Type your Query"> 

的search.php

<?php 
    $key=$_GET['key']; 
    $array = array(); 
    $con=mysql_connect("localhost","root",""); 
    $db=mysql_select_db("gs_dev",$con); 
    $query=mysql_query("select * from dmdkh_posts where post_title LIKE '%{$key}%'"); 
    $query2=mysql_query("select * from dmdkh_posts where post_title LIKE '%in%'"); 

    //THIS OUTPUT WORKS! I get all titles. 
    //echo $query2; 
    /*while ($row = mysql_fetch_array($query2, MYSQL_ASSOC)) { 
    printf("Title: %s ", $row["post_title"]); 
    }*/ 

    while($row=mysql_fetch_array($query, MYSQL_ASSOC)) 
    { 
     $array[] = $row['post_title']; 
    } 
    //THIS OUTPUT IS EMPTY! OUTPUT: [] 
    echo json_encode($array); 
?> 

我有兩個查詢。(查詢和QUERY2) QUERY2作品的輸出中,我得到了標題。 查詢的輸出是「[]」

在firebug中,我可以看到將從index.html轉換爲search.php的參數。

我希望有人能夠保護我。

+0

改變你的第一個查詢如果你可以,你應該[停止使用'mysql_ *'功能(http://stackoverflow.com/questions/12859942/why-shouldnt-i-use-mysql -functions功能於PHP)。他們不再被維護,並[正式棄用](https://wiki.php.net/rfc/mysql_deprecation)。瞭解[準備](http://en.wikipedia.org/wiki/Prepared_statement)[聲明](http://php.net/manual/en/pdo.prepared-statements.php),並考慮使用PDO ,[這真的不難](http://jayblanchard.net/demystifying_php_pdo.html)。 –

+0

[您的腳本存在SQL注入攻擊風險。](http://stackoverflow.com/questions/60174/how-can-i-prevent-sql-injection-in-php) –

+0

我知道那不是mysqli。這只是一個考驗。 如果我輸入3個字母輸入字段我的腳本工作... – cgee

回答

0

$query=mysql_query("select * from dmdkh_posts where post_title LIKE '%$key%'");