You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

PHP中年龄计算与嵌套IF语句失效问题排查

Troubleshooting Age Calculation & Purchase Restriction Issues

Let’s walk through fixing your broken age calculation and purchase restriction logic step by step—here’s why you’re seeing 0 days, 0 months, 0 years and how to fix it:

1. First: Confirm You’re Fetching DOB Data Correctly

The most common culprit here is that your code isn’t actually pulling the day, month, and year values from the database properly. If those variables are empty or unset, the date calculation will fail entirely.

Here’s how to safely retrieve and validate those fields with PDO:

// After connecting to your database
$stmt = $conn->prepare("SELECT day, month, year FROM users WHERE username = :username");
$stmt->bindParam(':username', $username);
$stmt->execute();
$user = $stmt->fetch(PDO::FETCH_ASSOC);

// Check if user exists and DOB fields are present
if (!$user || empty($user['day']) || empty($user['month']) || empty($user['year'])) {
    die("Error: Could not retrieve your date of birth.");
}

// Cast values to integers to avoid string parsing issues
$dobDay = (int)$user['day'];
$dobMonth = (int)$user['month'];
$dobYear = (int)$user['year'];

2. Create a Valid DateTime Object for the DOB

If your DOB values are invalid (e.g., 32 for a day, 13 for a month), the DateTime constructor will fail silently (or return false), leading to that zero difference result. Always validate the date and handle errors:

try {
    // Use YYYY-MM-DD format for reliable parsing
    $dob = new DateTime("$dobYear-$dobMonth-$dobDay");
} catch (Exception $e) {
    die("Error: Invalid date of birth. " . $e->getMessage());
}

$today = new DateTime();
$ageDiff = $today->diff($dob);

// Debug output to confirm the difference
echo "Age breakdown: " . $ageDiff->format('%d days, %m months, %y years') . "<br>";

3. Calculate the User’s Actual Current Age

The diff() method gives you a year count, but it doesn’t account for whether the user has had their birthday yet this year. For example, if today is March 1 and their birthday is March 5, they haven’t turned their next age:

$age = $ageDiff->y;
// Adjust age if birthday hasn't occurred yet this year
if ($today->format('md') < $dob->format('md')) {
    $age--;
}

echo "Your current age: " . $age . "<br>";

4. Fix the Purchase Restriction Logic

Now use the calculated age to enforce your restrictions. Here’s an example for 18+ items:

// Set this based on your product's requirement (15+ or 18+)
$minimumAge = 18;

// Check eligibility
if ($age >= $minimumAge) {
    echo "You’re eligible to add this item to your cart.";
    // Add your cart logic here
} else {
    echo "Sorry, you must be at least $minimumAge years old to purchase this item.";
    // Block cart addition
}

Common Mistakes to Avoid

  • Ignoring invalid dates: Always wrap DateTime creation in a try/catch to catch impossible dates (like Feb 30).
  • Using wrong date formats: YYYY-MM-DD is the only reliably parsed format for DateTime.
  • Skipping birthday check: Just using $ageDiff->y can overcount the age if the birthday hasn’t happened yet.
  • Not validating fetched data: Always check that your database query returned valid DOB fields before using them.

内容的提问来源于stack exchange,提问作者Ewelina Singh

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.26 09:55:35