donglian4464 2017-01-02 20:37
浏览 45
已采纳

动态CURDATE和INSERT INTO的问题

I'm trying to add a record to one of my tables. One of the columns is meant to be filled with a future date depending on the information entered, sometimes a month, sometimes a year.

I'm using CURDATE() + INTERVAL 1 MONTH/YEAR to get the future date.

However, when the record is added, the date appears as 0000-00-00.

This is the code I'm using:

if ($_POST['type'] == "month") {
    $expire = 'CURDATE() + INTERVAL 1 MONTH';
} else if ($_POST['type'] == "year") {
    $expire = 'CURDATE() + INTERVAL 1 YEAR';
}

$insertSQL = 'INSERT INTO users (dateAdded, name, email, promoEndDate) VALUES (now(), :name, :email, :expire)';
$rsInsert = $pdo->prepare($insertSQL);
$rsInsert->bindParam(':name', $_POST['name'], PDO::PARAM_STR);
$rsInsert->bindParam(':email', $_POST['email'], PDO::PARAM_STR);
$rsInsert->bindParam(':expire', $expire, PDO::PARAM_STR);
$rsInsert->execute();

I have previously used CURDATE without binding and it has worked, but I need the interval to depend on the user's choice.

I have also tried using $rsInsert->bindValue(':expire', $expire, PDO::PARAM_STR) but I get the same result.

Any help would be appreciated.

Thanks.

  • 写回答

1条回答 默认 最新

  • dongpo2002 2017-01-02 20:57
    关注

    This might be a little hacky, but since you aren't using any user entered parameters in that particular insert statement not terrible.

    if ($_POST['type'] == "month") {
        $expire = 'CURDATE() + INTERVAL 1 MONTH';
    } else if ($_POST['type'] == "year") {
        $expire = 'CURDATE() + INTERVAL 1 YEAR';
    }
    
    $insertSQL = 'INSERT INTO users (dateAdded, name, email, promoEndDate) VALUES (now(), :name, :email, '. $expire .')';
    $rsInsert = $pdo->prepare($insertSQL);
    $rsInsert->bindParam(':name', $_POST['name'], PDO::PARAM_STR);
    $rsInsert->bindParam(':email', $_POST['email'], PDO::PARAM_STR);
    $rsInsert->execute();
    

    Not necessarily relevant to your question, but you should probably consider sanitizing your variables if they are coming in from $_POST as well as including a default case for post type, since if neither month or year are specified your variable won't be added causing a insert failure.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 对于知识的学以致用的解释
  • ¥50 三种调度算法报错 有实例
  • ¥15 关于#python#的问题,请各位专家解答!
  • ¥200 询问:python实现大地主题正反算的程序设计,有偿
  • ¥15 smptlib使用465端口发送邮件失败
  • ¥200 总是报错,能帮助用python实现程序实现高斯正反算吗?有偿
  • ¥15 对于squad数据集的基于bert模型的微调
  • ¥15 为什么我运行这个网络会出现以下报错?CRNN神经网络
  • ¥20 steam下载游戏占用内存
  • ¥15 CST保存项目时失败