gpt4 book ai didi

php - 年龄计算&如果在里面如果不工作/php

转载 作者:行者123 更新时间:2023-11-29 10:16:01 26 4
gpt4 key购买 nike

我正在尝试将三个单独的数据库列转换为日期(日、月、年)并计算年龄,以便只有 15 或 18 岁以上的用户才能购买某些产品。下面的代码不起作用,因为它回显“0 天、0 个月、0 年”,但仍将产品添加到购物篮中。这意味着年龄计算不起作用,我的第一个 if 语句也不起作用。

<?php
$username = $_SESSION['solentuser'];
echo "$username's account!<br>";

$conn = new PDO("mysql:host=localhost;dbname=u;","u","p");

$productID= htmlentities($_GET['ID']);

//startdate
$result=$conn->prepare("SELECT * FROM users WHERE username=:username");
$result->bindParam(":username",$username);
$result->execute();
$row=$result->fetch();

$birthdate = $row['yearofbirth'] . $row['monthofbirth'] . $row['dayofbirth'];
$presentdate = date('Ymd');

$birthday = new DateTime($birthdate);
$currentdate = new DateTime($presentdate);

$age = $birthday->diff($currentdate);

echo $age->format('<br>%d Days %m Months %y Years<br>');

//enddate

$results=$conn->prepare("SELECT * FROM products where ID=:productID");
$results->bindParam(":productID",$productID);
$results->execute();
$row=$results->fetch();

if($row['agelimit'] <= $age){

if($row['stocklevel'] >= 1){

$result=$conn->prepare("INSERT INTO basket(productID,username,qty) values(:productID,:username,1)");
$result->bindParam(":productID",$productID);
$result->bindParam(":username",$username);
$result->execute();

$result=$conn->prepare("UPDATE products SET stocklevel=stocklevel-1 WHERE ID=:productID");
$result->bindParam(":productID",$productID);
$result->execute();

echo "You have successfully added this product to your basket!";
}
else{
echo "This product is out of stock!";
}
}
else{
echo "You are not old enough to purchase this product!";
}
//print_r($conn->errorInfo());
?>

关于错误在哪里有什么建议吗?我读到可以在 if 语句内编写 if 语句,那么为什么这个不起作用呢?

谢谢!

最佳答案

我会回显 $birthdate并验证那里有一个有效的日期。 (我们没有返回个位数,日期 2009-05-04 被表示为 '2009'、'5' 和 '4',这样当我们连接它们时,我们得到 200954 ,或者可能是额外的空格。(我们没有看到三个单独列的数据类型。)

我们可以尝试在其中添加一些分隔符,这样我们就会得到 2009-5-4 ,我们可能可以使用正确的格式字符串将其转换为日期时间。

如果我有单独的月、日和年值,我会使用 PHP mktime ,然后从中创建一个 DateTime 对象。

(MySQL 确实提供了 DATE 数据类型,它允许非常大范围的有效日期,并且不允许存储无效日期。存储三个单独的列来表示单个日期似乎是错误的方法(如果我实际上需要单独的月份和日期列(以允许对某些查询建立索引),我会在 birthdate DATE 列之外添加这些列,而不是代替它,并使用触发器来保持值与 birthdate 列同步。)

<小时/>

此外,$age是一个 DateInterval 对象。您似乎知道我们可以使用 format提取整数年数的方法。

$age_yrs = $age->format('%y');

我们猜测数据库列 age_limit是整数年。

if( $row['agelimit'] <= $age_yrs ) {

就在 if 语句之前,我们可以确认我们认为正确的内容实际上是正确的...

echo " age_yrs=" . $age_yrs;
echo " row_age_limit=" . $row['age_limit'];

仔细查看调试输出可以帮助我们确定问题是在 if 语句之前还是在 if 语句之后,因此我们不会在某个部分中追查问题。没有问题的代码,问题出在其他地方,在前一行。

<小时/>

我鼓励您培养调试您编写的程序所需的技能。看来您对变量所包含的内容做出了一些(错误的)假设。

添加echovar_dump在开发过程中,第一步是验证您认为正确的内容是否确实正确。

我建议您检查您编写的每一行代码,看看是否可能出错,尤其是在边缘情况下。

https://ericlippert.com/2014/03/05/how-to-debug-small-programs/

(StackOverflow 是一个问答社区,不是调试服务。)

关于php - 年龄计算&如果在里面如果不工作/php,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50109679/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com