将数据表与 PDO 一起使用

Posted

技术标签:

【中文标题】将数据表与 PDO 一起使用【英文标题】:Using DataTables With PDO 【发布时间】:2021-12-29 21:09:00 【问题描述】:

我正在尝试使用 PDO 将数据库中的数据插入到 DataTables 中,但遇到了一些麻烦。

当进入我的浏览器控制台时,fetch.php 正在返回:

"draw":1,"recordsTotal":0,"recordsFiltered":1104,"data":[]

如果我将 SQL 查询放入 $connection->prepare() 而不是把它放在 $query 里面...即:$connection->prepare($query) 它会返回: "draw":1,"recordsTotal":1104,"recordsFiltered":1104,"data":[null,null,null,null,etc....]

这是我的代码

我的 html

            <thead>
              <tr>
                <th>CRN</th>
                <th>Course ID</th>
                <th>Course Name</th>
                <th>Professor</th>
                <th>Section</th>
                <th>Building</th>
                <th>Room</th>
                <th>Start Time</th>
                <th>End Time</th>
                <th>Day</th>
                <th>Seats</th>
              </tr>
            </thead>
          </table>

我的 JS:

var masterScheduleTable = $('#masterscheduleTEST').DataTable(
        "processing":true,
        "serverSide":true,
        "order":[],
        "ajax":
          url:"http://ec2-13-59-215-177.us-east-2.compute.amazonaws.com/panel/scripts/fetch.php",
          type:"POST"
        
     );

最后,我的 php (fetch.php)

<?php
  include("database.php");
  include("function.php");

  $query ="";
  $output =array();

  $query .="SELECT class.CRN, course.courseID, course.courseTitle, user.lastName, class.section, building.buildingName, room.roomNumber, period.startTime, period.endTime, day.weekday, class.seatsAvailable
              FROM
              course
              INNER JOIN
              class ON course.courseID = class.courseID
              INNER JOIN
              faculty ON class.facultyID = faculty.facultyID
              INNER JOIN
              user ON faculty.userID = user.userID
              INNER JOIN
              room ON class.roomNo = room.roomID
              INNER JOIN
              building ON room.buildingID = building.buildingID
              INNER JOIN
              timeSlot ON class.timeSlotID = timeSlot.timeSlotID
              INNER JOIN
              period ON timeSlot.period =period.periodID
              INNER JOIN
              day ON timeSlot.days =day.dayID";

  if(isset($_POST["search"]["value"]))
      $query .= 'WHERE class.CRN LIKE "%'.$_POST["search"]["value"].'%" ';
      $query .= 'OR course.courseID LIKE "%'.$_POST["search"]["value"].'%" ';
      $query .= 'OR course.courseTitle "%'.$_POST["search"]["value"].'%" ';
      $query .= 'OR user.lastName "%'.$_POST["search"]["value"].'%" ';
      $query .= 'OR class.section LIKE "%'.$_POST["search"]["value"].'%" ';
      $query .= 'OR building.buildingName "%'.$_POST["search"]["value"].'%" ';
      $query .= 'OR room.roomNumber LIKE "%'.$_POST["search"]["value"].'%" ';
      $query .= 'OR period.startTime LIKE "%'.$_POST["search"]["value"].'%" ';
      $query .= 'OR period.endTime LIKE "%'.$_POST["search"]["value"].'%" ';
      $query .= 'OR day.weekday LIKE "%'.$_POST["search"]["value"].'%" ';
      $query .= 'OR class.seatsAvailable LIKE "%'.$_POST["search"]["value"].'%" ';
    
  if(isset($_POST["order"]))
      $query .= 'ORDER BY '.$_POST['order']['0']['column'].' '.$_POST['order']['0']['dir'].' ';
    
  else
      $query .= 'ORDER BY course.courseTitle ASC, class.section ASC';
    
  if($_POST["length"] != -1)
   $query .= 'LIMIT ' . $_POST['start'] . ', ' . $_POST['length'];
  
  $statement = $connection->prepare($query);
  $statement->execute();
  $result = $statement->fetchAll();
  $data = array();
  $filtered_rows = $statement->rowCount();
  foreach($result as $row)
   $sub_array = array();
   $sub_array[] = $row["class.CRN"];
   $sub_array[] = $row["course.courseID"];
   $sub_array[] = $row["course.courseTitle"];
   $sub_array[] = $row["user.lastName"];
   $sub_array[] = $row["class.section"];
   $sub_array[] = $row["building.buildingName"];
   $sub_array[] = $row["room.roomNumber"];
   $sub_array[] = $row["period.startTime"];
   $sub_array[] = $row["period.endTime"];
   $sub_array[] = $row["day.weekday"];
   $sub_array[] = $row["class.seatsAvailable"];
   $data[] = $sub_array;
  
  $output = array(
   "draw"    => intval($_POST["draw"]),
   "recordsTotal"  =>  $filtered_rows,
   "recordsFiltered" => get_total_all_records(),
   "data"    => $data
  );
  echo json_encode($output);
 ?>

(函数.php)

<?php
function get_total_all_records()

 include("database.php");
 $servername = "localhost";
 $username = "phpmyadmin";
 $password = "Amir123!";
 $dbname = "System Designs";
 $connection = new PDO("mysql:host=$servername;dbname=$dbname", $username, $password);
 
 $statement = $connection->prepare("SELECT class.CRN, course.courseID, course.courseTitle, user.lastName, class.section, building.buildingName, room.roomNumber, period.startTime, period.endTime, day.weekday, class.seatsAvailable
             FROM
             course
             INNER JOIN
             class ON course.courseID = class.courseID
             INNER JOIN
             faculty ON class.facultyID = faculty.facultyID
             INNER JOIN
             user ON faculty.userID = user.userID
             INNER JOIN
             room ON class.roomNo = room.roomID
             INNER JOIN
             building ON room.buildingID = building.buildingID
             INNER JOIN
             timeSlot ON class.timeSlotID = timeSlot.timeSlotID
             INNER JOIN
             period ON timeSlot.period =period.periodID
             INNER JOIN
             day ON timeSlot.days =day.dayID
             ORDER BY course.courseTitle ASC, class.section ASC");
 $statement->execute();
 $result = $statement->fetchAll();
 return $statement->rowCount();


?>

【问题讨论】:

SQL 注入。使用占位符和参数。 【参考方案1】:

从 API 提取记录时,我在使用 DataTables ajax 函数时遇到问题。

相反,您可以使用 Ajax 提取数据并将结果填充到表中。

$.ajax(
        url: "url",
        type: "GET",
        dataType: "JSON",
        success: (e) => 
            var html = '';
            $(e).each(function(k, v) 
                // Build your table tbody here
                html += '<tr>'
                html += '<td></td>'
                html += '</tr>'
            );
            $('.table-request').DataTable().clear()
            $('.table-request').DataTable().destroy()
            $(".table-request tbody").html(html)
            $(".table-request").DataTable()
        ,
        error: () => 
        
    )

建表后激活Datatable。

【讨论】:

以上是关于将数据表与 PDO 一起使用的主要内容,如果未能解决你的问题,请参考以下文章

如何在 PHP 中选择要与 PDO 一起使用的 MySQL 数据库?

将表单中的数据输入数据库 PDO

markdown 将PDO与IN子句一起使用

将 mysql_real_escape_string 与 PDO 一起使用(不连接到 localhost 服务器)

将 PDO 与 PostgreSQL 一起使用时如何忽略问号作为占位符

PDO?