Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

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!

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

<?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);
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading