2012-12-07 65 views
1

我在我的網站上構建了Live Search功能,我使用了W3schools示例,該功能非常完美。但是我想使用MySQL數據庫而不是XML文件,所以我正在開發一個代碼來獲取MySQL數據庫並將其轉換爲XML文件。使用Mysql和PHP進行Live Search搜索

<?php 

    header("Content-type: text/xml"); 

    include 'dbc.php'; 

     $query = "SELECT * FROM airports"; 
     $result = mysql_query($query, $link) 
     or die('Error querying database.'); 

    $xml_output = "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n"; 
    $xml_output .= "<entries>\n"; 

    for($x = 0 ; $x < mysql_num_rows($result) ; $x++){ 
     $row = mysql_fetch_assoc($result); 
     $xml_output .= "\t<entry>\n"; 
     $xml_output .= "\t\t<ident>" . $row['ident'] . "</ident>\n"; 
      // Escaping illegal characters 
      $row['name'] = str_replace("&", "&", $row['name']); 
      $row['name'] = str_replace("<", "<", $row['name']); 
      $row['name'] = str_replace(">", "&gt;", $row['name']); 
      $row['name'] = str_replace("\"", "&quot;", $row['name']); 
     $xml_output .= "\t\t<name>" . $row['name'] . "</name>\n"; 
     $xml_output .= "\t</entry>\n"; 
    } 

    $xml_output .= "</entries>"; 

    echo $xml_output; 

    ?> 

我收到此錯誤:

Warning: DOMDocument::load() [domdocument.load]: Start tag expected, '<' not found in /public_html/sql2xml.php, line: 11 in /public_html/livesearch.php on line 12 
no suggestion 

我看過的解釋:Avoid DOMDocument XML warnings in php 但我不知道如何解決,在我的代碼。有什麼建議麼?

+1

http://w3fools.com/ – Swadq

+0

首先是:總是使用mysqli擴展名;在PHP 5.5中,mysql將被棄用,mysqli具有更高的安全性和速度。 因此,它應該是:mysqli_query和mysqli_num_rows() –

+0

我改變了: $ xmlDoc-> load(「sql2xml.php」); 至 @ $ xmlDoc-> load(「sql2xml.php」); 它擺脫了錯誤,但現在我得到「沒有建議」,所以它不正常工作...... –

回答

0

這將需要的數據從「名稱」列在你的MySQL表,並把它變成一個陣列的同一陣列W3C學校查找您鍵入

$mysqli = new mysqli(HOST,USER,PASSWORD,DATABASE); 

/* check connection */ 
if ($mysqli->connect_errno) { 
    printf("Connect failed: %s\n", $mysqli->connect_error); 
    exit(); 
} 

$query = "SELECT * FROM table"; 
$result = $mysqli->query($query); 

while($row = $result->fetch_array()) 
{ 
    $a[]=$row["Name"]; 
} 

/* free result set */ 
$result->free(); 

/* close connection */ 
$mysqli->close(); 

// get the q parameter from URL 
$q = $_REQUEST["q"]; 

$hint = ""; 

// lookup all hints from array if $q is different from "" 
if ($q !== "") { 
    $q = strtolower($q); 
    $len=strlen($q); 
    foreach($a as $name) { 
     if (stristr($q, substr($name, 0, $len))) { 
      if ($hint === "") { 
       $hint = $name; 
      } else { 
       $hint .= ", $name"; 
      } 
     } 
    } 
} 

if (isset($q)) 
{ 
    // Output "no suggestion" if no hint was found or output correct values 
    echo $hint === "" ? "no suggestion" : $hint; 
} 
相關問題