2016-05-12 78 views
0

我試圖將$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(); 
+2

'$ countries [] = $ tom;' – Alex

回答

1

,因爲你已經assinged數據$國家錯誤的方式:

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

OHHH ..我的壞。非常感謝你的幫助。 – user3153327

+0

@ user3153327歡迎:)如果您發現它有用,請將其標記爲正確 –

0
$countries[] = $tom; 

用[]以可變的inicialization結束時,您將行添加到陣列。如果你在沒有[]的情況下這樣做,這只是在while循環中每次都是官方化的。

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(); 
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,你需要一個,因爲沒有mysqlnd mysqli的是不可用的反正。

相關問題