In this tutorial, I’ll walk you through the process of creating a calorie and nutrient counter using the FoodData Central API. This guide will help you build a web application that allows users to enter a food item and receive detailed nutritional information.
Video Here
Prerequisites
Before we start, ensure you have the following:
– Basic knowledge of PHP and HTML.
– An API key from FoodData Central.
– A local server environment (e.g., XAMPP, WAMP).
Step 1: Setting Up Your Project
Create a new PHP project and set up the following files:
– `index.php`
– `header.php`
– `footer.php`
– `error.php`
Step 2: Designing the HTML Form
In `index.php`, add the HTML form for users to enter food details:
<?php require_once('header.php'); ?> <?php include_once('error.php');?> <h1>Enter food to calculate nutrition</h1> <form action="" method="post"> <div class="form-group form-group-lg"> <label for="food">Enter food item be descriptive:</label> <input type="text" id="food" name="food" class="form-control" placeholder="red delicious apples / hard boiled eggs" required> </div> <div class="form-group form-group-lg"> <label for="amount">Enter how many:</label> <input type="number" id="amount" name="amount" class="form-control" required> </div> <div class="form-group form-group-lg"> <label for="measure">Choose Measurement Scale:</label> <select id="measure" name="measure" class="form-control" required> <option value="">Choose</option> <option value="240">Cup(s) 240 G</option> <option value="120">1/2 Cup(s) 120 G</option> <!-- Add more measurement options here --> </select> </div> <button type="submit" name="submit" class="btn btn-success">Add Food</button> </form> <?php require_once('footer.php'); ?>
Step 3: Handling Form Submission
In the same `index.php` file, add PHP code to handle form submission, make the API request, and process the response:
<?php if(isset($_POST['submit'])){ $food = htmlspecialchars($_POST['food']); $amount = htmlspecialchars($_POST['amount']); $measure = htmlspecialchars($_POST['measure']); $total = $measure * $amount; $api_url = 'https://api.nal.usda.gov/fdc/v1/foods/search'; $api_key = 'your_api_key_here'; $data = [ 'query' => $food, 'pageSize' => 1, 'api_key' => $api_key ]; $ch = curl_init($api_url . '?' . http_build_query($data)); curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); $response = curl_exec($ch); curl_close($ch); $result = json_decode($response, true); if (isset($result['foods'][0]['foodNutrients'])) { $nutrients = [ 'Potassium, K' => 'MG', 'Magnesium' => 'MG', 'Water' => 'G', 'Energy' => 'KCAL', 'Protein' => 'G', 'Total lipid (fat)' => 'G', 'Carbohydrate, by difference' => 'G', 'Fiber, total dietary' => 'G', 'Sugars, total including NLEA' => 'G', 'Cholesterol' => 'MG', 'Sodium, Na' => 'MG', 'Vitamin C, total ascorbic acid' => 'MG', 'Calcium, Ca' => 'MG', 'Iron, Fe' => 'MG' ]; foreach ($result['foods'][0]['foodNutrients'] as $nutrient) { $name = $nutrient['nutrientName']; $value = $nutrient['value']; $unit = $nutrient['unitName']; if (isset($nutrients[$name]) && $unit === $nutrients[$name]) { echo "The $name content for $food is $value $unit.<br>"; } } // Database insertion logic here } else { echo "<div class='alert alert-danger'>No information found for {$food}. Try again!</div>"; } } ?>
Step 4: Displaying Nutritional Information
The PHP script processes the response from the FoodData Central API and displays the relevant nutritional information. You can customize the output format as needed.
Step 5: Saving Nutritional Information to a Database
To save the nutritional information to a database, use the following code:
// Database connection $con = new mysqli('host', 'username', 'password', 'database'); // Check connection if ($con->connect_error) { die("Connection failed: " . $con->connect_error); } // Prepare and bind $stmt = $con->prepare("INSERT INTO food_plan (name, amount, measurement, total, calories, protein, fat, carbohydrates, fiber, sugars, cholesterol, sodium, vitamin_c, calcium, iron, potassium, magnesium) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)"); $stmt->bind_param("ssidddddddddddddd", $food, $amount, $measure, $total, $calories, $protein, $fat, $carbohydrates, $fiber, $sugars, $cholesterol, $sodium, $vitamin_c, $calcium, $iron, $potassium, $magnesium); // Execute the statement if ($stmt->execute()) { echo "<div class='alert alert-success'>Record inserted successfully</div>"; } else { echo "<div class='alert alert-danger'>Error: " . $stmt->error . "</div>"; } // Close connection $stmt->close(); $con->close();
Download All Scripts
$5 to download all scripts and database, click button below.
Conclusion
You now have a fully functional web application that can take a food item input, fetch its nutritional information using the FoodData Central API, and display and store the data. Customize and extend this project to fit your needs, such as adding more nutrient calculations or enhancing the UI.
Happy coding!
A1WEBSITEPRO Social Media Pages
Here are my social media pages, lets hook up!