PHP Multidimensional Array list a SQL database for easy handling in php

Advertisements

Trying to make a multidimensional array using PHP and a database on SQL and to have each value easy to call using HTML.
I dont need to draw the whole table but just getting some data from a specific cells based on row/id.

If i want to call row 1 and on that row cell one :

echo 'Contact : '.$contact[1][1].'<br>';

First im making the array and then adding the data to the array but im getting every detail as a separate item not as a multidimensional array!

<?php
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "myDB";

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

$sql = "SELECT * FROM `admin` ORDER BY id";
$result = $conn->query($sql);

$contact = array();
if ($result -> num_rows > 0) {
while($row = $result->fetch_assoc()) {
array_push($contact, $row["id"], $row["name"], $row["details"], $row["active"]);
}
}else{
echo "error";
}
$conn->close();

echo 'test 1'.$contact[3][3].'<br>';
echo 'test 2'.$contact[0][1].'<br>';

?>

Do i need to explain more or give any more details?

>Solution :

Each parameter value in array_push adds an element to the end of the array but obviously you don’t want them individually like that.

Instead create a new integer indexed array to hold the database values and append that to $contact:

while($row = $result->fetch_assoc()) {
     $rowValues = array_values($row);
     array_push($contact, $rowValues);
}

Leave a ReplyCancel reply