创建下一个按钮以循环遍历mysql表

时间:2015-07-14 02:15:14

标签: php mysql

我试图让下面的代码在while部分中有一个if / else语句?我尝试做类似的事情,如果结果是mysql表中的最后一行,则显示表中的第一行。否则显示$ id_related变量的id行。

我的目标是创建一个' next'按钮,实际上循环遍历数据库表 - 从id 1到10,当用户到达10并按下' next'按钮,它会回到id 1。

require('connect.php');
$id_related = mysqli_real_escape_string($db, $_GET['id']);
$sql_related = <<<SQL
    SELECT *
    FROM `article_img`
    WHERE `id` > '$id_related' ORDER BY id LIMIT 1 
SQL;

if(!$result = $db->query($sql_related)){
    die('There was an error running the query [' . $db->error . ']');
}
while($row = $result->fetch_assoc()){
echo '
        <a href="article.php?id='.$row['id'].'&size='.$row['size'].'">
            <div style="background-image: url('.$row['img'].');">
            </div>
        </a>

';

}

1 个答案:

答案 0 :(得分:0)

注意:

  • 您可以检查查询将返回的行数。如果当前$_GET['id'],例如10然后绑定您的查询,并返回0,请返回到表格的第一行id。因此,如果您想要扩展表格的行,您不必担心将来更新代码。
  • 您应该使用mysqli_*而不是deprecated mysql_* API。

您的connect.php代码:

$con = new mysqli("YourHost", "Username", "Password", "Database"); /* REPLACE NECESSARY DATA */

/* CHECK CONNECTION */
if (mysqli_connect_errno()) {
    printf("Connect failed: %s\n", mysqli_connect_error());
    exit();
}

你的主要代码:

require('connect.php'); /* YOUR CONNECTION */

if($stmt = $con->prepare("SELECT id,size,img FROM article_img WHERE id > ? ORDER BY id LIMIT 1")){
  $stmt->bind_param("i",$_GET["id"]); /* BIND THIS VARIABLE TO YOUR QUERY */
  $stmt->execute(); /* EXECUTE QUERY */
  $stmt->store_result(); /* NECESSARY WHEN GETTING THE NUMBER OF ROWS */
  $noofrows = $stmt->num_rows; /* GET NUMBER OF ROWS */
  if($noofrows == 0){ /* IF FOUND NO ROW GREATER THAN CURRENT CODE */
    /* GET THE FIRST ROW IN YOUR article_img */
    $stmt2 = $con->prepare("SELECT id,size,img FROM article_img ORDER BY id LIMIT 1")){
      $stmt2->execute();
      $stmt2->store_result();
      $stmt2->bind_result($id,$size,$img);
      $stmt2->fetch();
      $stmt2->close();
    } /* END OF SECOND PREPARED STATEMENT */
  } /* END OF IF $noofrows IS 0 */
  else { /* IF THERE IS A VALID NEXT ROW */
    /* GET THE NEXT PAGE */
    $stmt->bind_result($id,$size,$img); /* BIND THE RESULT TO THESE VARIABLES OF THE FIRST QUERY  */
    $stmt->fetch(); /* FETCH THE RESULT */
  } /* END OF ELSE */
  $stmt->close();
} /* END OF PREPARED STATEMENT */

echo '<a href="article.php?id='.$id.'&size='.$size.'">
        <div style="background-image: url('.$img.');">
        </div>
      </a>'; /* YOUR LINK TO NEXT PAGE */