PHP - 如果未设置值,则更新MySQL

时间:2014-07-14 08:40:20

标签: php mysql

我有以下内容: -

    $pdo = new SQL();
    $dbh = $pdo->connect(Database::$serverIP, Database::$serverPort, Database::$dbName, Database::$user, Database::$pass);

    if ($fieldBookingdate == NULL) {$fieldBookingdate = 'bookingdate';}
    if ($fieldReturndate == NULL) {$fieldReturndate = 'returndate';}
    if ($fieldBookingtime == NULL) {$fieldBookingtime = 'bookingtime';}
    if ($fieldReturntime == NULL) {$fieldReturntime = 'returntime';}
    if ($fieldPassengername == NULL) {$fieldPassengername = 'passengername';}
    if ($fieldPassengeremail == NULL) {$fieldPassengeremail = 'passengeremail';}
    if ($fieldPaddress == NULL) {$fieldPaddress = 'paddress';}
    if ($fieldVaddress == NULL) {$fieldVaddress = 'vaddress';}
    if ($fieldDaddress == NULL) {$fieldDaddress = 'daddress';}
    if ($fieldCartype == NULL) {$fieldCartype = 'cartype';}
    if ($fieldFlightnumber == NULL) {$fieldFlightnumber = 'flightnumber';}
    if ($fieldComments == NULL) {$fieldComments = 'comments';}

    $this->sql = "UPDATE  tblbookings SET bookingdate = '$fieldBookingdate', returndate = '$fieldReturndate', bookingtime = '$fieldBookingtime'
    returntime = '$fieldReturntime', passengername = '$fieldPassengername', passengeremail = '$fieldPassengeremail', paddress = '$fieldPaddress'
    vaddress = '$fieldVaddress', daddress = '$fieldDaddress', cartype = '$fieldCartype', flightnumber = '$fieldFlightnumber', comments = '$fieldComments' WHERE
    bookref = '$fieldBookingreference';";

基本上UPDATE将修改12个数据库字段,但可能只设置了11个值。 (MySQL的)

对于未设置的值,我知道您可以像UPDATE tblbookings SET bookingdate = bookingdate一样进行更新,它会起作用。但是,因为我在查询中的引号中有这些值,所以它更新为UPDATE tblbookings SET bookingdate = 'bookingdate' - 并且失败。

我怎么能让这个工作?

更新1: -

实施例

UPDATE  tblbookings SET bookingdate = 'bookingdate' WHERE

        bookref = 'BR1360'

我收到以下错误: -

1292 - 日期值不正确:第133行第'bookingdate'栏的'bookingdate'

如果我这样做: -

UPDATE  tblbookings SET bookingdate = bookingdate WHERE

        bookref = 'BR1360'

这将有效,并保留预订日期值。

2 个答案:

答案 0 :(得分:1)

错误是由查询中缺少逗号

引起的
bookingtime = '$fieldBookingtime'    returntime = '$fieldReturntime', 
                               //^ here the comma is missing

因此,作曲家正在尝试将bookingtime列设置为'fieldBookingtime' returntime...,这就像您传递的字符未被引号转义。

正如我在评论中已经解释过的那样,查询并没有失败,因为您按照自己的想法使用了引用。

答案 1 :(得分:0)

管理以使其工作如下: -

if ($fieldBookingdate == NULL) {$fieldBookingdate = "bookingdate = bookingdate";} else {$fieldBookingdate = "bookingdate = '$fieldBookingdate'";}

因此,如果未设置该值,它将保留字段(bookingdate = bookingdate),对于设置的值,它将更新为($fieldBookingdate = "bookingdate = '$fieldBookingdate'";