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

时间:2015-11-21 21:20:44

标签: php mysql mysqli

我正在使用表单运行简单的数据库搜索。我只对数据库中的一个表运行搜索,但我只运行一行。如果搜索出现两种或更多种可能性,则不会显示任何可能性。如何才能让它显示多行呢?

<?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>

1 个答案:

答案 0 :(得分:0)

您可以使用$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/>";
}