【问题标题】:Live Search With Mysql and PHP使用 Mysql 和 PHP 进行实时搜索
【发布时间】:2012-12-07 21:31:33
【问题描述】:

我正在我的网站上构建一个实时搜索功能,我使用了 W3schools 示例,它运行良好。但是我想使用 MySQL 数据库而不是 XML 文件,所以我正在编写一个代码来获取 MySQL 数据库并将其转换为 XML 文件。

   <?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 但我不知道如何在我的代码中解决这个问题。有什么建议吗?

【问题讨论】:

  • 第一件事是第一:总是使用mysqli扩展;在 php 5.5 中,mysql 将被弃用,mysqli 具有更高的安全性和速度。因此,应该是:mysqli_query 和 mysqli_num_rows()
  • 我改了:$xmlDoc->load("sql2xml.php"); @$xmlDoc->load("sql2xml.php");它摆脱了错误,但现在我得到“没有建议”,所以它不能正常工作......

标签: mysql xml domdocument


【解决方案1】:

这将从您的 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;
}

【讨论】:

    猜你喜欢
    • 2017-09-13
    • 1970-01-01
    • 2011-03-21
    • 2015-06-12
    • 2013-05-26
    • 2016-05-09
    • 2019-11-16
    • 1970-01-01
    • 2017-06-02
    相关资源
    最近更新 更多