Here’s a minimal end-to-end example. On the front end we’ll use a plain fetch() call; on the back end a tiny PHP script that queries tbl_users and returns JSON.
1. JavaScript (plain fetch + async/await)
/**
* Fetches a user profile by ID.
* @param {number|string} userId
* @returns {Promise<object>} Resolves to { name, email, dob, gender }
*/
async function getUserProfile(userId) {
const resp = await fetch(`/api/profile.php?user_id=${encodeURIComponent(userId)}`, {
method: 'GET',
headers: {
'Accept': 'application/json'
}
});
if (!resp.ok) {
throw new Error(`HTTP ${resp.status}: ${resp.statusText}`);
}
const data = await resp.json();
if (data.error) {
throw new Error(data.error);
}
return data;
}
// Usage example:
getUserProfile(42)
.then(user => {
console.log('Name: ', user.name);
console.log('Email:', user.email);
console.log('DOB: ', user.dob);
console.log('Gender:', user.gender);
})
.catch(err => console.error('Error fetching profile:', err));
2. PHP endpoint (/api/profile.php)
<?php
header('Content-Type: application/json; charset=utf-8');
// 1) Database credentials
$host = 'localhost';
$dbname = 'my_database';
$user = 'db_user';
$pass = 'db_pass';
// 2) Get & validate input
$userId = isset($_GET['user_id']) ? intval($_GET['user_id']) : 0;
if ($userId <= 0) {
echo json_encode(['error' => 'Invalid user_id']);
exit;
}
try {
// 3) Connect PDO
$pdo = new PDO(
"mysql:host={$host};dbname={$dbname};charset=utf8mb4",
$user,
$pass,
[PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION]
);
// 4) Prepare & execute
$stmt = $pdo->prepare(
"SELECT name, email, dob, gender
FROM tbl_users
WHERE id = :id
LIMIT 1"
);
$stmt->execute([':id' => $userId]);
// 5) Fetch & return
if ($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
echo json_encode($row);
} else {
echo json_encode(['error' => 'User not found']);
}
} catch (PDOException $e) {
// In prod you might log this instead of echoing
echo json_encode(['error' => $e->getMessage()]);
}
That’s it—just call getUserProfile(id) in JS, and your PHP script will query tbl_users and spit back the JSON { name, email, dob, gender }.