php - Creating next button to loop through mysql table -
i'm trying make below code have if/else statement in while section? i'm trying like, if result last row in mysql table display first row in table. otherwise display id row $id_related variable.
my goal create 'next' button esentially loops through database table - going id 1 10 , when user gets 10 , pushes 'next' button, goes id 1.
require('connect.php'); $id_related = mysqli_real_escape_string($db, $_get['id']); $sql_related = <<<sql select * `article_img` `id` > '$id_related' order id limit 1 sql; if(!$result = $db->query($sql_related)){ die('there error running 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> '; }
note:
- you can check number of rows query return. if current
$_get['id']
, example10
binds on query, , returns0
, go firstid
row of table. don't have worry updating code in future if want extend rows of table. - you should use
mysqli_*
rather deprecatedmysql_*
api.
your code 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(); }
and main code:
require('connect.php'); /* connection */ if($stmt = $con->prepare("select id,size,img article_img id > ? order id limit 1")){ $stmt->bind_param("i",$_get["id"]); /* bind variable query */ $stmt->execute(); /* execute query */ $stmt->store_result(); /* necessary when getting number of rows */ $noofrows = $stmt->num_rows; /* number of rows */ if($noofrows == 0){ /* if found no row greater current code */ /* first row in article_img */ $stmt2 = $con->prepare("select id,size,img article_img order 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 0 */ else { /* if there valid next row */ /* next page */ $stmt->bind_result($id,$size,$img); /* bind result these variables of first query */ $stmt->fetch(); /* fetch 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>'; /* link next page */
Comments
Post a Comment