How can one modify array column names after querying data from a SQL database in PHP?
When querying data from a SQL database in PHP, the column names in the resulting array are fixed and cannot be easily modified. To modify the array column names, you can create a new array with the desired column names and copy the data from the original array to the new array using a loop.
// Query data from the database
$query = "SELECT * FROM table";
$result = mysqli_query($connection, $query);
// Fetch data into an associative array
$data = mysqli_fetch_all($result, MYSQLI_ASSOC);
// Define new column names
$newColumnNames = array("new_column1", "new_column2", "new_column3");
// Create a new array with modified column names
$modifiedData = array();
foreach ($data as $row) {
$modifiedRow = array();
foreach ($row as $key => $value) {
$newKey = $newColumnNames[array_search($key, array_keys($row))];
$modifiedRow[$newKey] = $value;
}
$modifiedData[] = $modifiedRow;
}
// Now $modifiedData contains the data with modified column names
Keywords
Related Questions
- What are the potential security risks associated with passing variables from a form directly into an SQL query in PHP?
- How can PHP beginners avoid common pitfalls when working with database queries and updates?
- How can PHP handle user authentication without relying on a separate MySQL database for storing user credentials?