What is the importance of creating a 2-dimensional array from an SQL query in PHP?
When fetching data from an SQL query in PHP, it is common to store the results in a 2-dimensional array for easier manipulation and access. This allows you to organize the data in rows and columns, making it simpler to iterate over and extract specific values. By converting the SQL query results into a 2-dimensional array, you can efficiently work with the data in your PHP script.
// Connect to the database
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "database";
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
// Perform SQL query
$sql = "SELECT * FROM table";
$result = $conn->query($sql);
// Store results in a 2-dimensional array
$data = array();
if ($result->num_rows > 0) {
while($row = $result->fetch_assoc()) {
$data[] = $row;
}
}
// Close connection
$conn->close();
// Access data in the 2-dimensional array
foreach ($data as $row) {
echo $row['column1'] . " " . $row['column2'] . "<br>";
}