如何使用数组显示数据库中的所有数据

时间:2016-05-12 13:08:36

标签: php mysql arrays mysqli fetch

我试图将$countries连接到一个显示数据库中所有数据的数组,它只显示我输入的最后一个数据。无论如何,我可以显示所有这些数据吗?

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

$sql = "SELECT product_id, product_name , quantity FROM inventory";
$result = $conn->query($sql);

if ($result->num_rows > 0) {
     // output data of each row
     while($row = $result->fetch_assoc()) {
        $tom = array(" ". $row["quantity"] . $row["product_name"]);
         $countries = $tom;
     }
} else {
     echo "0 results";
}

$conn->close();

4 个答案:

答案 0 :(得分:1)

因为您以错误的方式将数据分配给$ country:

$countries = array();
if ($result->num_rows > 0) {
     // output data of each row
     while($row = $result->fetch_assoc()) {
        $tom = array(" ". $row["quantity"] . $row["product_name"]);
        $countries[] = $tom; // use []
     }
} else {
     echo "0 results";
}

答案 1 :(得分:0)

 $countries[] = $tom;

在变量的inicial化结束时使用[],向该数组添加一行。如果你在没有[]的情况下这样做,那么每次在while循环中它都是非常的。

答案 2 :(得分:0)

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

$sql = "SELECT product_id, product_name , quantity FROM inventory";
$result = $conn->query($sql);

if ($result->num_rows > 0) {
     // output data of each row
     while($row = $result->fetch_assoc())         
         $countries[] = " ". $row["quantity"] . $row["product_name"];     
} else {
     echo "0 results";
}

$conn->close();

答案 3 :(得分:0)

// create connection
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
$conn = new mysqli($servername, $username, $password, $dbname);

// get the data
$sql = "SELECT product_id, product_name, quantity FROM inventory";
$countries = $conn->query($sql)->fetch_all();

虽然它只有available with mysqlnd installations,但你需要一个,因为没有mysql,mysqli无论如何都无法使用。