MD ARIFUL HAQUE
Posted on August 1, 2024
A weather application that fetches and displays weather information from an API using PHP, jQuery, AJAX, Bootstrap, CSS, and MySQL.
Topics:
- PHP
- Weather API
- jQuery
- AJAX
- Bootstrap
- CSS
- MySQL
Step-by-Step Solution with Code Explanation
1. Directory Structure
weather-app/
│
├── config.sample.php
├── database/
│ └── weather_app.sql
├── src/
│ ├── api.php
│ ├── fetch_weather.php
│ └── index.php
├── css/
│ └── styles.css
├── js/
│ └── script.js
├── vendor/
│ └── (composer dependencies)
├── composer.json
├── README.md
└── .gitignore
2. Database Schema
database/database.sql:
CREATE DATABASE IF NOT EXISTS weather_app;
USE weather_app;
CREATE TABLE IF NOT EXISTS weather_logs (
id INT AUTO_INCREMENT PRIMARY KEY,
city VARCHAR(100) NOT NULL,
temperature FLOAT NOT NULL,
description VARCHAR(255) NOT NULL,
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
);
3. Configuration File
config.sample.php:
<?php
define('DB_HOST', 'localhost');
define('DB_NAME', 'weather_app');
define('DB_USER', 'root');
define('DB_PASS', '');
define('WEATHER_API_KEY', 'your_api_key_here');
define('WEATHER_API_URL', 'http://api.openweathermap.org/data/2.5/weather');
?>
4. Configure the Database Connection
db.php:
<?php
include 'config.php';
// Database configuration
$dsn = 'mysql:host='.DB_HOST.';dbname='.DB_NAME;
$options = [
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,
];
try {
$pdo = new PDO($dsn, DB_USER, DB_PASS, $options);
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
} catch (PDOException $e) {
die('Database connection failed: ' . $e->getMessage());
}
?>```
#### 5. **API Handling**
**src/api.php:**
```php
<?php
require_once '../db.php';
function getWeatherData($city) {
$url = WEATHER_API_URL . "?q=" . urlencode($city) . "&appid=" . WEATHER_API_KEY . "&units=metric";
$response = file_get_contents($url);
return json_decode($response, true);
}
if (isset($_GET['city'])) {
$city = $_GET['city'];
$weatherData = getWeatherData($city);
// Save to database
$stmt = $pdo->prepare('INSERT INTO weather_logs (city, temperature, description) VALUES (?, ?, ?)');
$stmt->execute([
$weatherData['name'],
$weatherData['main']['temp'],
$weatherData['weather'][0]['description']
]);
echo json_encode($weatherData);
}
?>
6. Fetching Weather Data
src/fetch_weather.php:
<?php
require_once '../db.php';
$stmt = $pdo->query('SELECT * FROM weather_logs ORDER BY created_at DESC');
$weatherLogs = $stmt->fetchAll(PDO::FETCH_ASSOC);
echo json_encode($weatherLogs);
?>
7. HTML and Frontend Code
index.html:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Weather App</title>
<link rel="stylesheet" href="css/styles.css">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css">
</head>
<body>
<div class="container">
<h1 class="mt-5">Weather App</h1>
<div class="form-group">
<label for="city">Enter city name:</label>
<input type="text" id="city" class="form-control">
</div>
<button id="getWeather" class="btn btn-primary">Get Weather</button>
<div id="weatherResult" class="mt-4"></div>
<h2 class="mt-5">Weather Logs</h2>
<div id="weatherLogs" class="mt-4"></div>
</div>
<script src="https://code.jquery.com/jquery-3.5.1.min.js"></script>
<script src="js/script.js"></script>
</body>
</html>
8. CSS Styles
css/styles.css:
body {
padding-top: 20px;
}
9. JavaScript and AJAX
js/script.js:
$(document).ready(function () {
$('#getWeather').click(function () {
var city = $('#city').val();
$.ajax({
url: 'api.php',
method: 'GET',
data: { city: city },
success: function (data) {
var weather = JSON.parse(data);
$('#weatherResult').html(
`<h3>Weather in ${weather.name}</h3>
<p>Temperature: ${weather.main.temp}°C</p>
<p>Description: ${weather.weather[0].description}</p>`
);
fetchWeatherLogs();
}
});
});
function fetchWeatherLogs() {
$.ajax({
url: 'fetch_weather.php',
method: 'GET',
success: function (data) {
var logs = JSON.parse(data);
var logsHtml = '<ul class="list-group">';
logs.forEach(function (log) {
logsHtml += `<li class="list-group-item">
<strong>${log.city}</strong>:
${log.temperature}°C,
${log.description}
<em>(${log.created_at})</em>
</li>`;
});
logsHtml += '</ul>';
$('#weatherLogs').html(logsHtml);
}
});
}
fetchWeatherLogs();
});
This solution covers the necessary steps to create a weather application using, jQuery, AJAX, Bootstrap, CSS, and MySQL. The provided code explanations and examples should help you understand and implement each part of the application.
Connecting Links
If you found this series helpful, please consider giving the repository a star on GitHub or sharing the post on your favorite social networks 😍. Your support would mean a lot to me!
If you want more helpful content like this, feel free to follow me:
Posted on August 1, 2024
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.