How to paginate a table of Mysql in PHP - php

I have a table in mysql.
Because it has many rows I want to put each 10 rows in a page and by clicking a link show me next 10 rows.
Is there any solution?

It was really really awesome http://www.phpsimplicity.com/tips.php?id=1
it is so simple! no need to work with huge classes! I'm Happy:D
<!DOCTYPE html>
<html lang="en">
<head>
<title>Paginate</title>
</head>
<body>
<form method='get'>
<?php
$connection = Mysql_connect( 'server', 'user', 'pass' );
if ( ! $connection ) {
echo 'connection is invalid';
} else {
Mysql_select_db( 'DB', $connection );
}
//Check if the starting row variable was passed in the URL or not
if ( ! isset( $_GET['startrow'] ) or ! is_numeric( $_GET['startrow'] ) ) {
//We give the value of the starting row to 0 because nothing was found in URL
$startrow = 0;
//Otherwise we take the value from the URL
} else {
$startrow = (int) $_GET['startrow'];
}
//This part goes after the checking of the $_GET var
$fetch = mysql_query( "SELECT * FROM sample LIMIT $startrow, 10" ) or
die( mysql_error() );
$num = Mysql_num_rows( $fetch );
if ( $num > 0 ) {
echo '
<table border=2>';
echo '
<tr>
<td>ID</td>
<td>Drug</td>
<td>quantity</td>
</tr>
';
for ( $i = 0; $i < $num; $i ++ ) {
$row = mysql_fetch_row( $fetch );
echo '
<tr>';
echo "
<td>$row[0]</td>
";
echo "
<td>$row[1]</td>
";
echo "
<td>$row[2]</td>
";
echo '
</tr>
';
}//for
echo '
</table>
';
}
//Now this is the link..
echo 'Next';
$prev = $startrow - 10;
//only print a "Previous" link if a "Next" was clicked
if ( $prev >= 0 ) {
echo 'Previous';
}
?>
</form>
</body>
</html>
By the way link of rickyduck was good too

I suggest checking out this link : http://php.about.com/od/phpwithmysql/ss/php_pagination.htm for basic pagination. Furthermore, if you have knowledge of javascript, you could use jQuery.

Related

How to display checked checkbox from database in php?

I want to display checked checkbox which are stored as values in a mysql database.
For now the table stores the value of the checkbox being checked in the database. The header and first column are fetched from three different tables in the database. While the values of the checked check-boxes gets saved in a same table.
Here's the code for inserting the data.
$active = "CourseReport";
require_once 'pages/header.php';
require_once './functions/schema-functions.php';
require_once './functions/report-functions.php';
$course = Schema::getCourseReport();
$objective = Schema::getObjective();
$goals = Schema::getGoals();
$mainobj = Schema::getMainObjectives();
$subobj = Schema::getSubObjectives();
?>
<form id="addReport" action ='./functions/report-functions.php' method="post">
<table id="table1" class="table table-hover">
<thead>
<?php
echo '<tr><th>Goals</th>';
for ($i = 0; $i < count($course); $i++) {
echo '<th id = "rotate1">'. $course[$i]->commonName . '</th>';
}
echo '</tr>';
?>
</thead>
<tbody>
<?php
for ($y = 0; $y < count($goals); $y++) {
echo '<tr class="clickable"><th class="toggle">Goal#'.$goals[$y]['GoalId'].':'." " .' '.$goals[$y]['Goals'].'</th>
</tr>';
?>
<?php
for( $z = 0; $z < count($mainobj); $z++){
if($mainobj[$z]['GoalId'] == $goals[$y]['GoalId']) {
echo '<tr class="expander"><th class=row-header>Objective#'.$mainobj[$z]['MainObjId'].':'." ".' '.$mainobj[$z]['MainObjectives'].'</th>
</tr>';
?>
<?php
for ($j = 0; $j< count($subobj); $j++) {
if($mainobj[$z]['MainObjId'] == $subobj[$j]['MainObjId']){
echo '<tr class="expander"><td class=row-header>'.$subobj[$j]['SubObjId'].' ) '.$subobj[$j]['SubObjectives'].' </td>';
for ($x = 0; $x < count($course); $x++) {
echo "<td><input name='check[]' type=checkbox value=c".$course[$x]->courseId."-o".$subobj[$j]['SubObjId']." id=checked></td>";
}
echo '</tr>';
}
}
}
}
}
?>
</tbody>
</table>
<button class="button" name= "submit" value= "Submit">Submit</button>
</form>
report-functions.php
if( isset( $_POST['submit'], $_POST['check'] ) ){
try{
require_once 'db-connect.php';
$conn = DatabaseConnection::getConnection();
$sql= " insert into `Report` (`ColRow`) values (:value) ";
$stmt = $conn->prepare( $sql );
if( $stmt ){
$conn->beginTransaction();
foreach( $_POST['check'] as $index => $value ) {
$result = $stmt->execute( [ ':value' => $value ] );
if( !$result ) {
echo '
<script>
alert("Error, please try submitting again. Error code 1");
window.history.back();
</script>';
}
}
$conn->commit();
echo '<script>
alert("Report was submitted successfully.");
window.location = ".../";
</script>';
}
} catch( Exception $e ){
$conn->rollback();
exit( $e->getMessage() );
}
I expect that once I submit the table, the table should load the same table with the checked checkboxes. I should be able to make the changes and submit the table over and over again.
Please comment if I need to provide any additional information.
When you display your page (in your first section of code), at some point you do this:
echo "<td><input name='check[]' type=checkbox value=c".$course[$x]->courseId."-o".$subobj[$j]['SubObjId']." id=checked></td>";
The value is set to:
value=c"c.$course[$x]->courseId."-o".$subobj[$j]['SubObjId']";
This value is where you get the checked or not value you mentioned in the comments (like c1-o1.1).
Right. So before you do that echo, add a new if condition.
$value = "c$course[$x]->courseId" . "-o$subobj[$j]['SubObjId']";
if (verify_checked($value)) {
$checked_code = "checked=\"checked\"";
}
else {
$checked_code = "";
}
echo "<td><input name='check[]' type=checkbox value=$value id=checked $checked_code ></td>";
The verify_checked(value) function does (from what I understand of your database, you keep the "grid location" of checked elements):
function verify_checked($value)
{
// Connect to the database if needed
// Perform: SELECT count($value) FROM Report
// If the result is >0, return TRUE
// Else return FALSE
}
The idea here is to query the database every time your are about to echo the <input> element.
Note for concatenating text, I find it more legible to put spaces around the . to clearly split what is part of the text and what is the concatenation dot.
As mentioned previously, indentation is critical for understanding of the different contexts. Until I indented your code, I had not realized how the different loops worked in relation to the others.

Very strange occurence mysql php blog

Ok so the problem I'm having is very strange. I have a blog website that displays a list of posts, and i made a system to select only 10 posts at a time. and yet on the second generated page 12 results are shown (the last 2 are duplicates)
//removed url because problem solved and i dont want to get sql injected
if you goto my project above and look at the second page of posts 12 entry's are shown with the last 2 being duplicates of the 3rd(and last) page...what is going on?! they should not be able to appear because the sql LIMIT function should restrict the displayed posts to 10.
here is the code for mainpage .php
<?php
session_start();
ob_start();
if ($_SERVER["REQUEST_METHOD"] == "POST"){//this works in my tests.
$low = 0;
$high = 10; //this loop/if method works in conjunction with the code at the bottom of this page
$e = 1;//starts at 1 because 1 itself is defined my default at the bottom of the page
while($_SESSION['i'] != $e){
$e++;
if (isset($_REQUEST["p$e"])){
$u = 1;
while($u != $e){
$u++;
$low = $low + 10;
$high = $high +10;
}
}
}}else{
$low = 0;
$high = 10;
}
?>
<!doctype html>
<!-- AUTHOR:JOSH FAIRBANKS -->
<html lang="en">
<head>
<meta charset="utf-8">
<title>Home Page</title>
<link rel="stylesheet" href="style.css">
</head>
<body>
<nav>
<ul>
<li><div id = "new">Create new post</div></li>
<li><div id = "veiw">Veiw posts</div></li>
</ul>
</nav>
<main>
<?php
$link = mysqli_connect( 'localhost', 'username', 'password' );
mysqli_select_db( $link, 'mydatabasename' );
$results = mysqli_query( $link, "SELECT LEFT(post, 575) as post FROM Users where verified = 1 ORDER BY `id` DESC LIMIT $low , $high" ); //this displayes all the posts that have been verified
while( $record = mysqli_fetch_assoc( $results ) ) {
$post = $record['post'];
$count = mysqli_affected_rows( $link );
//ORDER BY YEAR(Date) DESC, MONTH(Date) DESC, DAY(DATE) DESC
$post .= "</td></tr></table>";
print $post;
}
$vresults = mysqli_query( $link, "SELECT post FROM Users where verified = 1" );
while( $vrecord = mysqli_fetch_assoc( $vresults ) ) {
$vpost = $vrecord['post'];
$vcount = mysqli_affected_rows( $link );
$_SESSION['vcount'] = $vcount;
//
//these mirror variables arent seen and just are used to count the total amount of posts
//not just the ones on the page
}
mysqli_free_result( $results );
mysqli_close( $link );
?>
<form method = "post" action = "mainPage.php">
<table>
<tr><td>Page Number: </td><!--<td><input type = "submit" name = "p1" value = "1"></td>-->
<?php
$i = 0;
print "displaying low: $low high: $high";
for($j = 0; $j < $vcount; $j++) //modulus
{
if($j % 10 == 0)
{
$i++;
$_SESSION['i'] = $i;
print "<td><input type = 'submit' name ='"."p".$i. "' value = '$i'></td>";
}
}
?>
</tr>
</table>
</form>
</main>
</body>
</html>
I know this code is a bit of a mess :p but i swear it works except for this frustrating issue. any and all help appreciated.
I guess your problem at $high variable... Records per page always constant. But seems that you are increment in one place.
if ($_SERVER["REQUEST_METHOD"] == "POST"){//this works in my tests.
$low = 0;
$high = 10; //this loop/if method works in conjunction with the code at the bottom of this page
$e = 1;//starts at 1 because 1 itself is defined my default at the bottom of the page
while($_SESSION['i'] != $e){
$e++;
if (isset($_REQUEST["p$e"])){
$u = 1;
while($u != $e){
$u++;
$low = $low + 10;
$high = 10;
}
}
}}else{
$low = 0;
$high = 10;
}
?>

PHP while loop split into two

I'm running a while loop which is taking rows from mySQL and echo'ing them out. Pretty standard. However, there needs to be different HTML markup for the first item, next two items, then it continues as normal into the while loop.
Currently, my while loop looking something like this:
while( ( $row = mysql_fetch_object( $result ) ) !== false )
{
// Places ad based of predefined variable frequency
if ($ad == $adFrequency){
echo '<div class="one-advertisement-article clearfix">';
echo '<div class="grid_9 suffix_2"><img src="http://placehold.it/263x75/000000/ffffff"></div>';
echo '<div class="grid_1"><a class="navigate-right-icon ss-icon" href="#">navigateright</a></div>';
echo '</div>';
$ad = 0;
}
echo '<div class="one-news-article clearfix">';
if( $row->imagelibid )
{
$imageid = intval( $row->imagelibid );
$image_result = mysql_query( "SELECT * FROM imagelib WHERE id = {$imageid}", $db );
$image_row = mysql_fetch_object( $image_result );
$image_url = "http://www.#.com/slir/w280/imagelib/" . $image_row->id . "_" . $image_row->filename;
echo '<div class="grid_4"><img src="'.$image_url.'"></div>';
}
else {
echo '<div class="grid_4"><div class="news-placeholder"><span class="ss-icon">ellipsischat</span></div></div>';
}
echo '<div class="grid_7">';
echo '<h2>'.$row->title.'</h2>';
$published_date = date('D, d M Y', strtotime($row->datein));
echo '<p class="published-date">'.$published_date.'</p>';
echo '</div>';
echo '<div class="grid_1">';
echo '<div class="news-item-vertical-sep"> </div>';
echo '<p></p>';
echo '</div>';
echo '</div>';
$ad++;
}
This works fine, but I need to take the first three news items and use this:
echo ' <div class="one-news-featured-article clearfix">';
echo ' <div class="grid_12">';
if( $row->imagelibid )
{
$imageid = intval( $row->imagelibid );
$image_result = mysql_query( "SELECT * FROM imagelib WHERE id = {$imageid}", $db );
$image_row = mysql_fetch_object( $image_result );
$image_url = "http://www.#.com/slir/w280/imagelib/" . $image_row->id . "_" . $image_row->filename;
echo '<div class="large-featured-image-container"><img src="'.$image_url.'">/div>';
}
echo ' <div>';
echo ' <h2>'.$row->title.'</h2>';
echo ' </div>';
echo ' </div>';
echo ' </div>';
echo ' <div class="grid_6">';
Any help? Essentially, it needs to apply the second code to the first three items in the query, then follow through with the code included in the current while loop - like an offset I guess.
Thanks,
R
This is quite simple. I hope I understood your question correctly:
$i = 0;
while ( ( $row = mysql_fetch_object( $result ) ) !== false ) {
if ($i < 3) {
// First code
} else {
// Second code
}
$i += 1;
}
Firstly, you should avoid using any mysql_ functions as they are all deprecated and will be removed from future versions of PHP. I'd recommend using PDO instead. See this tutorial to get started.
Then, it'll simply be a case of doing something like this:
foreach($db->query($query) as $index => $row) {
if ($index < 3) {
// first 3 items
} else {
// other items
}
}
You can do it easaly with an simple counter and an if statement:
$count = 0;
while(fetching) {
if($count < 3) {
// items 1, 2 and 3
} else {
// do normal
}
$count++;
}

Pulling Data in PHP from SQL Server

I have an issue with my script somewhere but do not know exactly where it is incorrect. Here is the code:
<title>Log</title>
</head>
<h1> Log </h1>
<form method="get" action="getlog.php">
<table width="300" border="0">
<tr>
<td> Forte ID:</td>
<td><select id="ForteID" name="ForteID">
<option value="nc4682">nc4682</option>
<option value="bs1441">bs1441</option>
<option value="sp3212">sp3212</option>
</select></td>
</tr>
</table>
<input type="submit" name="getLog" value="Get Log">
</form>
</head>
<body>
</body>
</html>
<?php
/*print_r($_POST);*/
$serverName = 'SRB-Nick_Desktop\SQLEXPRESS';
$connectionInfo = array('Database'=>'cslogs', 'UID'=>'cslogslogin', 'PWD'=>'123456');
$connection = sqlsrv_connect($serverName, $connectionInfo);
$query = 'SELECT ForteID, Disposition, appNumber, Finance_Num, Num_Payments, ACH_CC, Notes from logs';
$result = sqlsrv_query($connection,$query);
if (!$result)
{
$message = 'ERROR: ' . sqlsrv_errors();
return $message;
}
else
{
$i = 0;
echo '<html><body><table><tr>';
while ($i < sqlsrv_num_rows($result))
{
$meta = sqlsrv_fetch($result, $i);
echo '<td>' . $meta->name . '</td>';
$i = $i + 1;
}
echo '</tr>';
while ( ($row = sqlsrv_fetch_array($result)))
{
$count = count($row);
$y = 0;
echo '<tr>';
while ($y < $count)
{
$c_row = current($row);
echo '<td>' . $c_row . '</td>';
next($row);
$y = $y + 1;
}
echo '</tr>';
}
sqlsrv_free_stmt ($result);
echo '</table></body></html>';
}
sqlsrv_close( $connection);
?>
And this is what I get in result, no matter what is selected in the drop down box and hit the button get log.
nc4682 nc4682 Save Save asdf asdf fdas fdas 1 1 cc cc asdf asdf
bs1441 bs1441 LOC LOC AN00336862 AN00336862 None None 0 0 ach ach Backout Backout
nc4682 nc4682 Save Save AN00336862 AN00336862 easdf easdf 2 2 ach ach asdf asdf
sp3212 sp3212 Sale Sale NCXXXXXX1 NCXXXXXX1 none none 1 1 cc cc asdfasdfasdf asdfasdfasdf
Each column is duplicated. There are supposed to be 7 columns.
To only show the results from the drop down list you would append something like
WHERE ForteID = {$_GET['ForteID']}
to the end of your SQL statement.
sqlsrv_fetch_array() returns both a numeric array and an associative array by default.
Try specifying only one type of array
while ( $row = sqlsrv_fetch_array( $result, SQLSRV_FETCH_ASSOC ))
To use your dropdpwn in the query.
$query = 'SELECT ForteID, Disposition, appNumber, Finance_Num, Num_Payments, ACH_CC, Notes FROM logs WHERE ForteID =' . $_GET['ForteID'];
Please be aware that without sanitizing the $_GET variable this query is vulnerable to sql injection.

Why isn't my MySQL data being displayed in my table?

Why is my MySQL data not being displayed in my table? Everything seems to work fine except that my data (which is a list of bird names and such) isn't showing up. I need some fresh eyes who can see where my mistake is, and yes I know that there are probably easier ways to do this, but this is what is required for my assignment, so please don't offer other ways to do this. All I need is help getting my data to populate in the HTML table. My PHP code is below:
PHP Code
<?php
$pageTitle = 'Mod06 Pagination| Jason McCoy ';
include('includes/header.inc.php');
include ('includes/db_connect.inc.php');
$display = 8;
// Determine how many pages there are...
if (isset($_GET['p']) && is_numeric($_GET['p'])) { // Already been determined.
$pages = $_GET['pages'];
} else {
$query = "SELECT COUNT(birdID) FROM birds";
$result = #mysqli_query($dbc, $query);
$row = #mysqli_fetch_array($result, MYSQLI_NUM);
$records = $row[0];
}
// Calculate the number of pages...
if ($records > $display) {
$pages = ceil($records/$display);
} else {
$pages = 1;
}
// Determine where in the database to start returning results...
if (isset($_GET['s']) && is_numeric($_GET['s'])) {
$start = $_GET['s'];
} else {
$start = 0;
}
// Sort the columns
// Default is birdID
$sortDefault = 'birdID';
// Create an array for the columns
$sortColumns = array('birdID', 'nameGeneral', 'nameSpecific', 'populationTrend');
// Define sortable query ASC DESC
$sort = (isset($_GET['sort'])) && in_array($_GET['sort'], $sortColumns) ? $_GET['sort']: $sortDefault;
$order = (isset($_GET['order']) && strcasecmp($_GET['order'], 'DESC') == 0) ? 'DESC' : 'ASC';
// Run the query
$query = "SELECT birdID, nameGeneral, nameSpecific, populationTrend FROM birds ORDER BY $order LIMIT $start, $display";
$result = #mysqli_query($dbc, $query);
?>
<!-- Table header: -->
<table align="center" cellspacing="0" cellpadding="5" width="80%">
<tr>
<th><a href='index.php?sort=birdID&order=<?php echo $order == 'DESC' ? 'ASC' : 'DESC' ?>'>Bird<?
if($_GET["order"]=="ASC" && $_GET["sort"]=="birdID"){
echo '<img src="images/downArrow.jpg" id="birdASC" name="birdASC" style="margin:-15px 0 0 13px;" width="18px" height="18px">';
} else {
echo '<img src="images/upArrow.jpg" id="birdDESC" name="birdDESC" style="margin:-15px 0 0 13px;" width="18px" height="18px">';
}?></a></th>
<th><a href='index.php?sort=nameGeneral&order=<?php echo $order == 'DESC' ? 'ASC' : 'DESC' ?>'>General Name<?
if($_GET["order"]=="ASC" && $_GET["sort"]=="nameGeneral"){
echo '<img src="images/downArrow.jpg" id="nameGeneralASC" name="nameGeneralASC" style="margin:-15px 0 0 13px;" width="18px" height="18px">';
} else {
echo '<img src="images/upArrow.jpg" id="nameGeneralDESC" name="birdDESC" style="margin:-15px 0 0 13px;" width="18px" height="18px">';
}?></a></th>
<th><a href='index.php?sort=nameSpecific&order=<?php echo $order == 'DESC' ? 'ASC' : 'DESC' ?>'>Name Specific<?
if($_GET["order"]=="ASC" && $_GET["sort"]=="nameSpecific"){
echo '<img src="images/downArrow.jpg" id="nameSpecificASC" name="nameSpecificASC" style="margin:-15px 0 0 13px;" width="18px" height="18px">';
} else {
echo '<img src="images/upArrow.jpg" id="nameSpecificDESC" name="birdDESC" style="margin:-15px 0 0 13px;" width="18px" height="18px">';
}?></a></th>
<th><a href='index.php?sort=populationTrend&order=<?php echo $order == 'DESC' ? 'ASC' : 'DESC' ?>'>Population Trend<?
if($_GET["order"]=="ASC" && $_GET["sort"]=="populationTrend"){
echo '<img src="images/downArrow.jpg" id="populationTrendASC" name="populationTrendASC" style="margin:-15px 0 0 13px;" width="18px" height="18px">';
} else {
echo '<img src="images/upArrow.jpg" id="populationTrendDESC" name="birdDESC" style="margin:-15px 0 0 13px;" width="18px" height="18px">';
}?></a></th>
</tr>
<?php
// Display the database results in the table...
while ($row = #mysqli_fetch_array($result, MYSQL_ASSOC)) {
echo '<tr>
<td align="left">$row[birdID]</td>
<td align="left">$row[nameGeneral]</td>
<td align="left">$row[nameSpecific]</td>
<td align="left">$row[populationTrend]</td>
<tr>';
}
echo '</table>';
mysqli_close($dbc);
// Make the links to other pages, if necessary.
if ($pages > 1) {
echo '<br /><p>';
$currentPage = ($start/$display) + 1;
// If it's not the first page, make a Previous button:
if ($currentPage != 1) {
echo 'Previous ';
}
// Make all the numbered pages:
for ($i = 1; $i <= $pages; $i++) {
if ($i != $currentPage) {
echo '' . $i . ' ';
} else {
echo $i . ' ';
}
} // End of FOR loop.
// If it's not the last page, make a Next button:
if ($currentPage != $pages) {
echo 'Next';
}
echo '</p>';
}
include('includes/footer.inc.php');
?>
</div>
</body>
</html>
Change this one $row[birdID] to $row['birdID'] for all, you missed ''.
use " inside echo like this, you have used ' because of that the value from database is not displayed.
while ($row = #mysqli_fetch_array($result, MYSQL_ASSOC)) {
echo "<tr>
<td align=\"left\">$row[birdID]</td>
<td align=\"left\">$row[nameGeneral]</td>
<td align=\"left\">$row[nameSpecific]</td>
<td align=\"left\">$row[populationTrend]</td>
<tr>";
}
Sorry, if a bit concise, typing from a phone...
'$row[birdID]'
and the other parts should be properly rewritten as:
'$row['birdID']'
as birdID is a string, not a variable name.
Though PHP uses this as a string, if there is no variable with that name in the current scope.
Always use quotes around a string literal array index. For example, $foo['bar'] is
correct, while $foo[bar] is not. But why? It is common to encounter this kind of
syntax in old scripts
from the PHP documentation: http://php.net/manual/en/language.types.array.php
EDIT somebody pointed out the single quotes used in echo too, that is a problem too. with single quotes, PHP will not interpret the content of the string, whereas with double quotes, PHP will parsde it, and use the values properly.

Categories