【问题标题】:how can I display all the data from database using an array如何使用数组显示数据库中的所有数据
【发布时间】:2016-09-08 08:19:45
【问题描述】:

我正在尝试将$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();

【问题讨论】:

  • $countries[] = $tom;

标签: php mysql arrays mysqli fetch


【解决方案1】:

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

$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";
}

【讨论】:

  • @user3153327 欢迎 :) 如果您觉得有用,请标记为正确
【解决方案2】:
 $countries[] = $tom;

使用 [] 在变量初始化的末尾添加一行到该数组。如果不使用 [],则每次在 while 循环中进行初始化。

【讨论】:

    【解决方案3】:
    // 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();
    

    【讨论】:

      【解决方案4】:
      // 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,但你需要一个,因为没有mysqlnd mysqli 无论如何都无法使用。

      【讨论】:

        猜你喜欢
        • 2011-12-31
        • 1970-01-01
        • 2015-09-20
        • 1970-01-01
        • 2021-09-19
        • 2015-04-04
        • 2017-12-25
        • 2018-10-15
        • 1970-01-01
        相关资源
        最近更新 更多