How can PHP be used to calculate and display the percentage of storage space used by a user in a MySQL database?

To calculate and display the percentage of storage space used by a user in a MySQL database, you can query the database to get the total storage space allocated to the user and the amount of storage space currently in use. Then, you can calculate the percentage by dividing the used space by the total space and multiplying by 100. Finally, you can display this percentage to the user.

// Connect to MySQL database
$connection = mysqli_connect("localhost", "username", "password", "database");

// Query to get total storage space allocated to user
$totalQuery = "SELECT SUM(data_length + index_length) AS total_space FROM information_schema.tables WHERE table_schema = 'your_database_name'";
$totalResult = mysqli_query($connection, $totalQuery);
$totalRow = mysqli_fetch_assoc($totalResult);
$totalSpace = $totalRow['total_space'];

// Query to get amount of storage space currently in use by user
$usedQuery = "SELECT SUM(data_length + index_length) AS used_space FROM information_schema.tables WHERE table_schema = 'your_database_name'";
$usedResult = mysqli_query($connection, $usedQuery);
$usedRow = mysqli_fetch_assoc($usedResult);
$usedSpace = $usedRow['used_space'];

// Calculate percentage of storage space used
$percentage = ($usedSpace / $totalSpace) * 100;

// Display the percentage to the user
echo "Percentage of storage space used: " . round($percentage, 2) . "%";

// Close database connection
mysqli_close($connection);