How can SQL be utilized in creating a BMI calculator in PHP?
To create a BMI calculator in PHP using SQL, you can store user data in a database and then retrieve it to calculate the BMI. You can use SQL queries to fetch the user's height and weight from the database and then perform the BMI calculation in PHP.
<?php
// 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);
}
// Fetch user's height and weight from the database
$sql = "SELECT height, weight FROM users WHERE user_id = 1";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
// Calculate BMI
$row = $result->fetch_assoc();
$height = $row['height'];
$weight = $row['weight'];
$bmi = $weight / (($height/100) * ($height/100));
echo "BMI: " . $bmi;
} else {
echo "User data not found";
}
$conn->close();
?>