PHP试图向sql发送单独的日期和时间变量

时间:2015-12-05 18:37:34

标签: php sql date time formatting

我正在尝试将两个单独的变量发送到mysql数据库,一个用于日期,一个用于时间。目前,这两个变量都是字符串,mysql列的格式为日期和时间类型。我应该如何在sql查询中发送变量?

编辑:添加了错误

  

致命错误:带有消息的未捕获异常'PDOException'   'SQLSTATE [23000]:完整性约束违规:1452无法添加或   更新子行:外键约束失败(jk497.Booking,   CONSTRAINT Booking_ibfk_1 FOREIGN KEY(PerfDate,PerfTime)参考   性能(PerfDate,PerfTime))'in   第58行/home/cuc/jk497/public_html/bookingReceipt.php

我的代码

$time = "17:00:00"; 
$sql = "insert into Booking values (':id', ':date', ':time', ':fullName', ':email', ':rowNum', ':numSeats', ':bookedSeats');"; 
$handle = $conn->prepare($sql); 
$handle->execute(array(':id' => $_SESSION['id'], ':date' => $SESSION['date'], ':time' => $time, ':fullName' => $_SESSION['fullName'], ':email' => $_SESSION['email'], ':rowNum' => $seatIndex, ':numSeats' => $_SESSION['numSeats'], ':bookedSeats' => $_SESSION['bookedSeats']));

1 个答案:

答案 0 :(得分:0)

this示例我将首先更改您拥有的代码:

$sql = "insert into Booking ('id','date','time','fullName','email','rowNum','numSeats','bookedSeats') values (:id,:date,:time,:fullName,:email,:rowNum,:numSeats,:bookedSeats)"; 
$handle = $conn->prepare($sql); 
$handle->bindParam(':id',$_SESSION['id']);
$handle->bindParam(':date',$SESSION['date']);
$handle->bindParam(':time',$time);
$handle->bindParam(':fullName',$_SESSION['fullName']);
$handle->bindParam(':email',$_SESSION['email']);
$handle->bindParam(':rowNum',$seatIndex);
$handle->bindParam(':numSeats',$_SESSION['numSeats']);
$handle->bindParam(':bookedSeats',$_SESSION['bookedSeats']);

$handle->execute();

需要考虑的事项:

  1. 查询具有特定的查询顺序

    insert into table () values ();
    insert into table values (); //is what you had (this is not correct and will never work afaik)
    
  2. 您将值作为数组发送,不确定原因,但您可以发送值

    bind_param($_SESSION['id'],$SESSION['date'],$time,$_SESSION['fullName'],$_SESSION['email'],$seatIndex,$_SESSION['numSeats'],$_SESSION['bookedSeats'])
    
  3. 从头开始使用您的查询

    变化:

    $sql = "insert into Booking values (':id', ':date', ':time', ':fullName', ':email', ':rowNum', ':numSeats', ':bookedSeats');"; 
    

    进入

    $sql = "insert into Booking (id,date,time,fullName,email,rowNum,numSeats, bookedSeats) values (:id,:date,:time,:fullName,:email,:rowNum,:numSeats, :bookedSeats)";