当我运行数据库搜索时,如何让mysqli_fetch_row返回多行


How do I get mysqli_fetch_row to return more than one row when I run a database search

我使用表单运行一个简单的数据库搜索。我只对数据库中的一个表运行搜索,但我只运行一行。如果搜索中出现两种或两种以上的可能性,则不会显示其中任何一种。如何在应该显示多行的情况下使其显示多行?

<?php
$servername = "localhost";
$username = "xxx";
$password = "xxx";
$dbname = "oldga740_SeniorProject";

// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
     die("Connection failed: " . $conn->connect_error);
}

// If there is a search variable try to search database
if(isset($_POST['search'])) {
    $searchq = $_POST['search'];
    $searchq = preg_replace("#[^0-9a-z]#i","",$searchq);
    $sql = "SELECT * FROM Customers WHERE Client LIKE '%$searchq%'";
        if ($result = $conn->query($sql)) {
    /* fetch object array */
    while ($row = $result->fetch_row()) {
        printf ("%s (%s)'n", $row[0], $row[1]);
    }
    /* free result set */
    $result->close();
}


}
?>
<html>
<head>
</head>
<body>
<form action="Index.php" method="post">
  <input type="text" name="search" placeholder="Search...." />
  <input type="submit" value=">>" />
</form>

</body>
</html>

您可以使用$result->fetch_all(MYSQLI_ASSOC)来获取行数组(关联数组的数组)。

示例:

// This will display all the rows returned by your SQL query.
$elements = $result->fetch_all(MYSQLI_ASSOC);
foreach($elements as $row) {
    var_dump($row);
    echo "<br/>";
}