PHP MySQLi Pagination LIMIT,WHERE和ORDER BY`date` DESC问题

时间:2017-07-06 13:55:56

标签: php mysqli pagination

我创建的项目不是为了盈利而且有分页问题。第一个想法是"加载更多" < - 但它只是在梦中。也许MySQL语法错了。如何修复此代码?也许有更好的解决方案?我尝试了所有组合" ..",' ..',``。这也可以通过使用SQL注入来利用吗?

  MySQLi connection:


$mysqli = new mysqli('localhost','root','','tablename');
if ($mysqli->connect_error) {
    die('Error : ('. $mysqli->connect_errno .') '. $mysqli->connect_error);
}
/* Change character set to utf8 */
if (!$mysqli->set_charset("utf8")) {
    printf("Error loading character set utf8: %s\n", $mysqli->error);
    exit();
}

  Paggination:

  $items_per_page = 5;  
  $login = $_SESSION['login'];
  $per_page = $items_per_page;
  if (isset($_GET['page'])) {
  $page = $_GET['page'];
  }else {
  $page = 1;
  }
  $start_from = ($page-1) * $per_page;
  //Selecting the data from db   
  $date = $mysqli->query("SELECT post_id FROM posts WHERE posts_author = '.$login.' ORDER BY `date` DESC LIMIT $start_from, $per_page");
  while($row = $date->fetch_array()){
  echo $row["post_id"];
  }
  //



  //Select all from DB
  $query = $mysqli->query("SELECT post_id FROM posts WHERE posts_author='$login' ORDER BY date DESC");
  $result = mysqli_query($mysqli, $query);
  $total_records = mysqli_num_rows($result);
  $total_pages = ceil($total_records / $per_page);
  //Going to first page
  echo '<a href="' .ABSOLUTE_URL. '/post/1">first page</a> '; 
  for ($i=1; $i<=$total_pages; $i++){
  echo '<a href="' .ABSOLUTE_URL. '/post/'.$i.'">'.$i.'</a> ';
  };
  // Going to last page
  echo '<a href="' .ABSOLUTE_URL. '/post/'.$total_pages.'">last page</a> ';

1 个答案:

答案 0 :(得分:0)

您的代码可以被利用, 您应该考虑使用virtualhttp://php.net/manual/en/mysqli.real-escape-string.php

对于错误,我在这里看到:

mysqli_real_escape_string

您使用带有//Selecting the data from db $date = $mysqli->query("SELECT post_id FROM posts WHERE posts_author = '.$login.' ORDER BY `date` DESC LIMIT $start_from, $per_page"); while($row = $date->fetch_array()){ echo $row["post_id"]; } 点的单引号,而不是使用双引号,您的查询应该可以正常执行。

如果你遇到其他一些问题,请更新答案你在哪里停留,什么不起作用以及你尝试了什么。