duanfei1987 2012-04-10 16:36
浏览 46

难以使用PHP文档中的SQL查询数据库中的两个表


I'm really struggling to get my code to work, and I can't figure out why.

I have a database in my PHPMyAdmin and it contains 2 tables:

  1. tennisCourts
    courtID
    courtName
    bookingFee

  2. tenniscourts_Availability
    courtID
    court_dateBooked

I am writing a PHP program using PEAR repository, and I am struggling to create code that allows me to:

Display All courtNames and their corresponding bookingFee BASED ON users search date ONLY IF the courtName is not already booked by another user.

Here is my current code:-

    $CHOSEN_BOOKING_DATE =  $_GET['user_dateField']; //GET's input data from user form in my other html document.


    $database->setFetchMode(MDB2_FETCHMODE_ASSOC);


    $myQuery = "SELECT * FROM tennisCourts, tenniscourts_Availability WHERE court_dateBooked != $CHOSEN_BOOKING_DATE";


$queryResult =& $db->query($myQuery);

    if (PEAR::isError($queryResult)) {
        die($queryResult->getMessage());
    }

    echo '<table>';
    while ($Col =& $queryResult->fetchRow()) {  
        echo '<td>'.$queryResult['courtName'].'</td>';
        echo '<td>'.$queryResult['bookingFee'].'</td>'; 
        echo '<td>'.$queryResult['court_dateBooked'].'</td>';
    }

?>

The code above displays all the courtNames and BookingFee's for All court_dateBooked fields in my database. I cant get it to display the courtNames and bookingFee only if it isn't booked. If it is booked it should return "sorry no courts found on this date".

I am still new to PHP and SQL so forgive me if I have not made myself clear. I have been researching online and various sources say to use SQL UNION OR JOIN? Could someone please enlighten me on how they could be used in context to my scenario? I really appreciate any help. Thank you for checking out my question.

  • 写回答

1条回答 默认 最新

  • donglinxia1541 2012-04-10 16:39
    关注

    Try this:

    $myQuery = "
        SELECT c.courtName
             , c.bookingFee
             , a.court_dateBooked
          FROM tennisCourts AS c
     LEFT JOIN tenniscourts_Availability AS a ON c.id = a.courtID
         WHERE a.court_dateBooked != '" . $CHOSEN_BOOKING_DATE ."'";
    

    Make sure you sanitize and escape $CHOSEN_BOOKING_DATE properly before executing your query. Since it looks like you're using PDO you should be using prepared statements for this.

    评论

报告相同问题?

悬赏问题

  • ¥15 微信小程序协议怎么写
  • ¥15 c语言怎么用printf(“\b \b”)与getch()实现黑框里写入与删除?
  • ¥20 怎么用dlib库的算法识别小麦病虫害
  • ¥15 华为ensp模拟器中S5700交换机在配置过程中老是反复重启
  • ¥15 java写代码遇到问题,求帮助
  • ¥15 uniapp uview http 如何实现统一的请求异常信息提示?
  • ¥15 有了解d3和topogram.js库的吗?有偿请教
  • ¥100 任意维数的K均值聚类
  • ¥15 stamps做sbas-insar,时序沉降图怎么画
  • ¥15 买了个传感器,根据商家发的代码和步骤使用但是代码报错了不会改,有没有人可以看看