How can PHP be used to manipulate and store data retrieved from a MySQL database?
To manipulate and store data retrieved from a MySQL database using PHP, you can use the MySQLi or PDO extension to establish a connection to the database, execute queries to retrieve data, manipulate the data as needed, and then insert or update the data back into the database.
// Establish a connection to the MySQL database
$mysqli = new mysqli("localhost", "username", "password", "database_name");
// Check connection
if ($mysqli->connect_error) {
die("Connection failed: " . $mysqli->connect_error);
}
// Retrieve data from the database
$result = $mysqli->query("SELECT * FROM table_name");
// Manipulate the data
while($row = $result->fetch_assoc()) {
// Manipulate data here as needed
}
// Insert or update data back into the database
$mysqli->query("INSERT INTO table_name (column1, column2) VALUES ('value1', 'value2')");
$mysqli->query("UPDATE table_name SET column1 = 'new_value' WHERE column2 = 'value'");
// Close the connection
$mysqli->close();