【问题标题】:Using MYSQLI in php to search data and return results as XML [duplicate]在php中使用MYSQLI搜索数据并以XML形式返回结果[重复]
【发布时间】:2013-06-27 10:53:37
【问题描述】:

我正在制作一个脚本,如果其中一个列与关键字匹配,它将为每一行返回数据库中的所有列。例如。在下面的示例中,将返回与单词 tap 匹配的所有行。然后我想将结果呈现为 xml。下面的代码似乎有效,并且 totalResults 显示找到的匹配数。如何循环遍历每个结果并通过 SQL 查询呈现所有匹配的数据?

   $query = 'tap';

    //connect to the database
$db = new mysqli('localhost', $username, $password, $database );
if($db->connect_errno > 0){
    die('Unable to connect to database [' . $db->connect_error . ']');
}

//query the database    
$sqlQuery = "select * from skus
where
`id` like '%$query%' OR
`name` like '%$query%' OR
`description` like '%$query%' OR
`ean` like '%$query%' OR
`price` like '%$query%' OR
`wasPrice` like '%$query%' OR
`deliveryCost` like '%$query%' OR
`deliveryTime` like '%$query%' OR
`stockAvailability` like '%$query%' OR
`skuAvailableInStore` like '%$query%' OR
`skuAvailableOnline` like '%$query%' OR
`channel` like '%$query%' OR
`manufacturersPartNumber` like '%$query%' OR
`specificationsModelNumber` like '%$query%' OR
`featuresBrand` like '%$query%' OR
`imageUrl` like '%$query%' OR
`thumbnailUrl` like '%$query%' OR
`features` like '%$query%' OR
`url` like '%$query%' OR
`productHierarchy` like '%$query%'";
if(!$result = $db->query($sqlQuery)){
    die('There was an error running the query [' . $db->error . ']');
}

    Header('Content-type: text/xml');

echo '<?xml version="1.0" encoding="utf-8"?>';

echo '<totalResults>Total results: ' . $result->num_rows . '</totalResults>';

//close the database connection
$db->close();

【问题讨论】:

  • 将元数据排除在标签正文之外。如果您有 50 个结果,您的 XML 应该是 &lt;totalResults&gt;50&lt;/totalResults&gt;
  • @Burhan Khalid:我觉得可以关闭(所以得到了我的投票,很好的副本),但是与 Mysqli 相关的一些细节并未包含在该答案中。

标签: php xml mysqli


【解决方案1】:

$result 返回从查询中找到的每一列的数组。

所以,你只需要像这样循环数组:

//loop through all columns of the result

foreach($result as $key => $value)

{

      // Output : { key : "name", value : "tap" } if "name" === "tap"

      echo "{ key : " . $key . ", result : " + $value + "}";

}

你只需要将你希望的方式插入到xml中

【讨论】:

    【解决方案2】:

    我不得不使用 mysqli_fetch_assoc

    完成的代码:

    //connect to the database
    $db = new mysqli('localhost', $username, $password, $database );
    if($db->connect_errno > 0){
        die('Unable to connect to database [' . $db->connect_error . ']');
    }
    
    //query the database    
    $sqlQuery = "select * from skus
    where
    `id` like '%$query%' OR
    `name` like '%$query%' OR
    `description` like '%$query%' OR
    `ean` like '%$query%' OR
    `price` like '%$query%' OR
    `wasPrice` like '%$query%' OR
    `deliveryCost` like '%$query%' OR
    `deliveryTime` like '%$query%' OR
    `stockAvailability` like '%$query%' OR
    `skuAvailableInStore` like '%$query%' OR
    `skuAvailableOnline` like '%$query%' OR
    `channel` like '%$query%' OR
    `manufacturersPartNumber` like '%$query%' OR
    `specificationsModelNumber` like '%$query%' OR
    `featuresBrand` like '%$query%' OR
    `imageUrl` like '%$query%' OR
    `thumbnailUrl` like '%$query%' OR
    `features` like '%$query%' OR
    `url` like '%$query%' OR
    `productHierarchy` like '%$query%'";
    
    //run query
    if ($result = mysqli_query($db, $sqlQuery)) {
    
        Header('Content-type: text/xml');
    
        echo '<?xml version="1.0" encoding="utf-8"?>';
    
        echo '<results>';
    
        echo '<skus>';
    
        //fetch associative array 
        while ($row = mysqli_fetch_assoc($result)) {
            echo '<sku>';
    
                echo '<id>' . htmlspecialchars($row["id"]) . '</id>';
                echo '<ean>' . htmlspecialchars($row["ean"]) . '</ean>';
                echo '<name>' . htmlspecialchars($row["name"]) . '</name>';
                echo '<description>' . htmlspecialchars($row["description"]) . '</description>';
                echo '<features>' . htmlspecialchars($row["features"]) . '</features>';
                echo '<productHierarchy>' . htmlspecialchars($row["productHierarchy"]) . '</productHierarchy>';
                echo '<url>' . htmlspecialchars($row["url"]) . '</url>';
                echo '<price>' . htmlspecialchars($row["price"]) . '</price>';
                echo '<wasPrice>' . htmlspecialchars($row["wasPrice"]) . '</wasPrice>';
                echo '<deliveryCost>' . htmlspecialchars($row["deliveryCost"]) . '</deliveryCost>';
                echo '<deliveryTime>' . htmlspecialchars($row["deliveryTime"]) . '</deliveryTime>';
                echo '<stockAvailability>' . htmlspecialchars($row["stockAvailability"]) . '</stockAvailability>';
                echo '<skuAvailableInStore>' . htmlspecialchars($row["skuAvailableInStore"]) . '</skuAvailableInStore>';
                echo '<skuAvailableOnline>' . htmlspecialchars($row["skuAvailableOnline"]) . '</skuAvailableOnline>';
                echo '<channel>' . htmlspecialchars($row["channel"]) . '</channel>';
                echo '<manufacturersPartNumber>' . htmlspecialchars($row["manufacturersPartNumber"]) . '</manufacturersPartNumber>';
                echo '<specificationsModelNumber>' . htmlspecialchars($row["specificationsModelNumber"]) . '</specificationsModelNumber>';
                echo '<featuresBrand>' . htmlspecialchars($row["featuresBrand"]) . '</featuresBrand>';
                echo '<imageUrl>' . htmlspecialchars($row["imageUrl"]) . '</imageUrl>';
                echo '<thumbnailUrl>' . htmlspecialchars($row["thumbnailUrl"]) . '</thumbnailUrl>';
    
    
            echo '</sku>';
    
        }
    
        echo '</skus>';
    
    }
    
    //close the database connection
    $db->close();
    
    echo '</results>';
    

    【讨论】:

    • 是的,因为每个教程都应该向您展示(或者如果您的 PHP 版本不是 end-of.life [PHP 5.4+],则只需使用 foreach)。使用为您创建 XML 以及迭代每个结果行的 XML 库,您甚至可以将此代码减少到仅 4 行左右。
    • 将您添加为答案,以便更好地了解我的意思:stackoverflow.com/a/17389749/367456
    【解决方案3】:

    你问的不是很具体,所以我会笼统地回答这个问题。

    您通过迭代mysqli_result objectTraversable)来循环 Mysqli 查询的结果(当前非 End-Of-Live 版本的 PHP 为 5.4 和 5.5) - 所以 非常 易于使用:

    foreach ($result as $row) 
    {
        ...
    

    对于 XML 输出,您应该使用 XMLWriter library,因为它可以满足您的需求。例如上面的foreach

    foreach($result as $row)
    {
        $writer->startElement('sku');
    
        foreach($row as $name => $value) {
            $writer->startElement($name);
            $writer->text($value);
            $writer->endElement();
        }
    
        $writer->endElement();
    }
    

    完整示例一目了然(我的 SQL 查询和数据库不同,但我猜应该不会让人头疼):

    $mysql = new Mysqli('localhost', 'testuser', 'test', 'test');
    if ($mysql->connect_errno) {
        throw new Exception(sprintf("Mysqli: (%d): %s", $mysql->connect_errno, $mysql->connect_error));
    }
    
    $sqlQuery = 'SELECT * FROM config';
    if (!$result = $mysql->query($sqlQuery)) {
        throw new Exception(sprintf('Mysqli: (%d): %s', $mysql->errno, $mysql->error));
    }
    
    header('Content-type: text/xml');
    $writer = new XMLWriter();
    
    $writer->openUri('php://output');
    $writer->startDocument();
    $writer->startElement('results');
    $writer->startElement('skus');
    
    foreach($result as $row)
    {
        $writer->startElement('sku');
    
        foreach($row as $name => $value) {
            $writer->startElement($name);
            $writer->text($value);
            $writer->endElement();
        }
    
        $writer->endElement();
    }
    
    $writer->endDocument();
    

    希望这会有所帮助。如果您还没有 PHP 5.4,请获取它。如果这是一个问题,您可以将 Mysqli 结果也转换为其他 PHP 版本的迭代器,如in my answer to "PHP mysqli_result: Use Traversable interface with fetch_object" 所述。让我知道这是否会给您带来任何问题。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2011-09-18
      • 2017-11-09
      • 2017-04-02
      • 1970-01-01
      • 2018-11-06
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多