0

I'm trying to connect $countries to an array that will display all the data from my database, it only displays the last data I entered.Is there anyway I can display all of them?

// 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();
1
  • 2
    $countries[] = $tom; Commented May 12, 2016 at 13:11

4 Answers 4

1

because you have assinged data to $countries with wrong manner:

$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";
}
Sign up to request clarification or add additional context in comments.

1 Comment

@user3153327 welcome :) mark it correct if you found it useful
0
 $countries[] = $tom;

With [] at the end of inicialization of variable you add a row to that array. If you do it without [], it's just inicialization every time in while loop.

Comments

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();

Comments

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();

Although it's only available with mysqlnd installations, you need one, because without mysqlnd mysqli is unusable anyway.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.