在php中使用MYSQLI来搜索数据并将结果作为XML返回

时间:2013-06-29 23:06:24

标签: php xml mysqli

我想要创建一个脚本,如果其中一列与关键字匹配,它将返回数据库中每行的所有列。例如。在下面的示例中,返回所有与单词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();

3 个答案:

答案 0 :(得分:2)

你没有特别提出要求,所以我会广泛回答这个问题。

通过遍历mysqli_result object Traversable来循环遍历Mysqli查询的结果(使用当前非现场版本的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"所示。如果这会导致您遇到任何问题,请告诉我。

答案 1 :(得分:1)

我不得不使用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>';

答案 2 :(得分:-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中插入你想要的