Pagination of records from MySQL Database - php

I have a script that counts how many records it sees on the page :
<script>
document.write(document.getElementById('moon').rows.length-1);
document.write (' ');
document.write (' of ');
document.write (' ');
document.write(document.getElementById('moon').rows.length-1);
document.write (' pages');
</script>
How would I use this to paginate 10 records at a time?
Perhaps using a styling such as display:none or something and then linking to these hidden divs on the "page" count.
Thanks
Edit:
I have tried to use a PHP Mysql Query to do this with num_rows, but it always throws out errors even when I am getting data!
2nd EDIT
Ok, I am pulling the information and displaying it with:
<table class="std" id="moon" border="0" cellpadding="0" cellspacing="0">
<tr>
<?php
$pcounter = 1;
$userID = LedDB::getInstance()->get_user_id_by_name($_SESSION['user']);
$presult = LedDB::getInstance()->get_page_by_campaign_id($campaignID);
$i=0;
while ($row = mysqli_fetch_array($presult)):
$style = "";
if($i%2==0)
{
$style = 'style="background-color: #EFEFEF"';
}
echo "<tr ".$style.">";
echo "<td class='camp' style='padding-left:10px;'><b><a href='editPage.php?pageID=" .htmlentities($row['pid']) ."&campaignID=" .htmlentities($row['campaignid']) ."' class='camp'> Page" . $pcounter . "</a></b></td>";
echo "<td style='padding-left:10px;'></td>";
echo "<td style='padding-left:10px;'></td>";
echo "<td></td>";
echo "<td></td>";
$pageID = $row['pid'];
//The loop is left open
?>
<td>
<div class="buttons">
<form name="editPage" action="editPage.php" method="GET">
<input type="hidden" name="campaignID" value="<?php echo $campaignID ?>"/>
<input type="hidden" name="pageID" value="<?php echo $pageID ?>"/>
<button type="submit" name="editPage" value="Edit" class="blue" >
<img src="images/edit.png" width="20" height="20"></button>
</form>
</div>
</td>
<td>
<form name="deletePage" action="deletePage.php" method="POST">
<input type="hidden" name="pageID" value="<?php echo $pageID; ?>"/>
<div class="buttons">
<button type="submit" name="deletePage" value="Delete" class="negative">
<img src="images/delete_x.png" width="20" height="20"></button>
</div>
</form>
</td>
<?php
echo "</tr>\n";
$pcounter++;
$i++;
endwhile;
mysqli_free_result($presult);
?>
</table>
Where $presult = LedDB::getInstance()->get_page_by_campaign_id($campaignID); is this:
public function get_page_by_campaign_id($campaignID) {
$campaignID = $this->real_escape_string($campaignID);
return $this->query("SELECT pid,campaignid,message_text,message FROM pages WHERE campaignid =" . $campaignID );
}
Whenever I try to wrap this in a pagination class, it either returns a 0 value or just bombs out my entire script with sql_num_rows() errors...
That is the reason I thought javascript pagination would be the best solution in this case.

There are several examples on the web to get you started, thats where I'd start:
http://www.phpclasses.org/search.html?words=pagination&x=0&y=0&go_search=1
http://www.phpsnaps.com/snaps/view/php-pagination-class/
http://www.phpbuilder.com/board/showthread.php?t=10283679
http://phpsense.com/2007/php-pagination-script/

Related

Why I am unable to pass a variable in PHP

I got a function.php which is in inc/function. This function contains a table. This table is generated in an MySQL statement.
My idea is quite easy - the user is able to go through the table with a next button and a back button.
Here is my code:
<div class="container-fluid">
<form action="fda.php" method="post">
<div class="row">
<div class="col-md-6 col-md-offset-3">
<p>Bitte beantworten Sie die folgenden Fragen:</p>
<table class="table table-striped">
<thead>
<tr>
<th>Nr.</th>
<th width="250">Frage</th>
<?php tbl_description() ?>
</tr>
</thead>
<tbody>
<?php tbl_showPage() ?>
</tbody>
</table>
</div>
<div class="col-md-6 col-md-offset-3 text-center">
<form action="functions.php" method="post">
<input type="submit" name="back" value="Zurück" id="back" class="btn btn-default">
<input type="submit" name="go" value="Weiter" id="go" class="btn btn-default">
<!--<input type="submit" value="FDA auswerten" class="btn btn-default">-->
</div>
</div>
</form>
</div>
this is the part from the fda.php file! Everything is working cool except the increase of the mysql statement which is in the function.php.
While clicking on next the statement should be "refreshed" and show me the 2nd page of the table. Its like an questionaire.
This is the code of the function php.
function tbl_showPage(){
global $mysqlhost, $mysqluser, $mysqlpwd, $mysqldb;
$connection=mysqli_connect($mysqlhost, $mysqluser, $mysqlpwd) or die ("Verbindungsversuch fehlgeschlagen");
mysqli_select_db($connection, $mysqldb) or die("Konnte die Datenbank nicht waehlen.");
if(isset($_POST['go']))
{
$page++;
}
elseif($_POST['back'])
{
$page--;
}
//if(isset($page)){
if($page<1)
{
$sql_tbl_questions = "SELECT * FROM `questions` where istAktiv='1' && dimension='1'";
}
elseif($page>9)
{
$sql_tbl_questions = "SELECT * FROM `questions` where istAktiv='1' && dimension='9'";
}
else
{
$sql_tbl_questions = "SELECT * FROM `questions` where istAktiv='1' && dimension=$page";
}
//}
$quest_query = mysqli_query($connection, $sql_tbl_questions) or die("Anfrage nicht erfolgreich");
$i = 0;
while ($question = mysqli_fetch_array($quest_query)) {
$i++;
echo '<tr>';
echo '<th>'.$i.'</th>';
echo '<th>'.$question['question'].'</th>';
echo '<th class="text-center"><input type="radio" name="'.$question['dimension'].'_question_'.$question['id'].'" value="0" required></th>';
echo '<th class="text-center"><input type="radio" name="'.$question['dimension'].'_question_'.$question['id'].'" value="2.5"></th>';
echo '<th class="text-center"><input type="radio" name="'.$question['dimension'].'_question_'.$question['id'].'" value="5"></th>';
echo '<th class="text-center"><input type="radio" name="'.$question['dimension'].'_question_'.$question['id'].'" value="7.5"></th>';
echo '<th class="text-center"><input type="radio" name="'.$question['dimension'].'_question_'.$question['id'].'" value="10"></th>';
echo '</tr>';
$dimensions = $question['dimension'];
}
echo '<tr>';
echo '<th></th>';
echo '<th>Kommentar/Ihre Anmerkung</th>';
echo '<th class="text-center" colspan=5><textarea rows=3 cols=50 name="Kommentar"></textarea></th>';
echo '</tr>';
echo '<input type="hidden" name="gesamt" value="'.$i.'">';
echo '<input type="hidden" name="dimensions" value="'.$dimensions.'">';
echo '<input type="hidden" name="size" value="'.$_POST['size'].'">';
echo '<input type="hidden" name="branche" value="'.$_POST['branche'].'">';
}
Maybe I am missing something? I really hope someone can help me!
I see two problems here:
The form is submitting both 'back' and 'go' variables, regardless of which one was clicked.
The PHP script is not tracking the $page variable across page loads. (If it is not tracked, it will re-initialize to 0 every time the page is loaded.)
Try having your form tell the PHP script which page to load:
<form action="functions.php" method="post">
<button type="submit" name="page" value="<?php echo $page - 1; ?>">Zurück</button>
<button type="submit" name="page value="<?php echo $page + 1; ?>">Weiter</button>
</form>
Then in your PHP, you would just check for the value of $_POST['page']
if(!empty($_POST['page'])) {
$page = intval($_POST['page']);
} else {
$page = 1;
}
You will also need to make the $page variable visible from the fda.php script into the function.php script. You could do that using global $page; next to your mysql variables. (That's not an optimal or clean way of doing things, but it would be the easiest addition to your code.)

why does mymysqli delete button doesn't work?

I am trying to delete a product from the table, but it does not work.
Is the script wrong? How can I correct it?
include_once('connection.php');
include_once('functions.php');
if(isset($_POST['delete'])){
mysqli_query( $conDB, "DELETE FROM products WHERE name='$_POST[hidden]'");
};
$page = (int)(!isset($_GET["page"]) ? 1 : $_GET["page"]);
if ($page <= 0) $page = 1;
$per_page = 10; // Set how many records do you want to display per page.
$startpoint = ($page * $per_page) - $per_page;
$statement = "products ORDER BY id DESC";
$results = mysqli_query($conDB, "SELECT * FROM {$statement} LIMIT {$startpoint} , {$per_page}");
if (mysqli_num_rows($results) != 0) {
while ($row = mysqli_fetch_array($results)) {
$name = $row['name'];
?>
<tr>
<td align="left" colspan='2' ><big style="color:red" ><b><?php echo $row['name']?></b></big><td>
</tr>
<tr>
<td align="left" colspan='2'><big style="color:333333"><b><?php echo $row['category']?></b> / <?php echo $row['subcategory']?></big></td>
</tr>
<tr>
<td style="vertical-align:top" >
<?php echo "<img border=3 width= 300px height =250px src=\"products/" . $row['picture']>?>"<br />
</td>
<td style="vertical-align:top">
<?php echo nl2br($row['description'])?>
</td>
</tr>
<tr>
<td> <input type="hidden" name="hidden" value="$name" ><input type="submit" name="delete" onClick='return confirmDelete()' value='Delete Product'></td>
When I delete the "delete product" the confirmation will show if I will delete it. but after the confirmation. it does not delete the selected row from the table.
There is no show of error from php after the confirmation. Why is it happening and
how can I fix it?
Looking at the hidden value, it seems its not written properly in the markup:
<input type="hidden" name="hidden" value="$name" >
<!-- ^ literal string, not a variable value -->
Should be:
<input type="hidden" name="hidden" value="<?php echo $name; ?>" />
Sidenote: Since you're already using mysqli, why not utilize prepared statements.
if(isset($_POST['delete'])) {
$delete = $_POST['delete'];
$del = $conDB->prepare('DELETE FROM products WHERE name = ?');
$del->bind_param('s', $delete);
$del->execute();
}
I suggest do it like this, remove the hidden input and use this instead:
<button type="submit" name="delete" onClick='return confirmDelete()' value="<?php echo $row['id']; ?>">Delete Product</button>
Just correct your input hidden field:
<input type="hidden" name="hidden" value="<?php echo $name; ?>" >
Try
echo "DELETE FROM products WHERE name='$_POST[hidden]'";
and then try executing the sql or modify
"DELETE FROM products WHERE name='".$_POST[hidden]."'"

updating mysql database after an entry is deleted

Working on deleting an entry from my database table.
Currently the delete is working. However it deletes the "id + 1"
My script populates a "delete " button right next to an entry populated from mysql table.
When I hit delete next to an entry, it deletes the item +1.
I think it has to do with the while loop, the way I populate items.
Any ideas on how to fix this?
<?php
while($row = mysqli_fetch_array($result)) : ?>
<tr>
</table border = '1'><br><table border = '1'><th>Subject</th><th>Sender</th> <th>Message</th><th>Delete</th>
<?php
echo "<tr><td>";
echo $row['subject'];
echo "<td>";
echo $row['sender'];
echo "<td>";
echo $row['msgText'];
echo "<td>";
?>
<form action="delete.php" method="post">
<input type="hidden" name="delete_id" value="<?php $_SESSION['id'] = $row['id']; ?>" />
<input type="submit" value="Delete" />
</form>
</tr>
<?php endwhile; ?>
here is the script in delete.php
<?php
session_start();
$id = $_SESSION['id'];
$con=mysqli_connect("localhost","root","","something");
$sql = "DELETE FROM `mailbox` WHERE `id`= '$id'";
$result = mysqli_query($con,$sql);
header('Location: loggedin.php');
?>
<input type="hidden" name="delete_id" value="<?php $_SESSION['id'] = $row['id']; ?>" />
change it to:
<input type="hidden" name="delete_id" value="<?php echo $row['id']; ?>" />
and in your delete.php, simply replace $_SESSION['id'] to $_POST['delete_id']
P/S: By the way, you've forgot to add session_start(); in your form's php, if you do really want to use it, but not a good idea for this time.
The $_SESSION['id'] gets overridden each time in the loop.
Why not just simply use $_POST["delete_id"] to retrieve row id.
Your Table Structure is wrong
<?php
while($row = mysqli_fetch_array($result)) :
?>
<tr>
<th>Subject</th>
<th>Sender</th>
<th>Message</th>
<th>Delete</th>
</tr>
<tr>
<?php
echo "<td>";
echo $row['subject'];
echo "</td><td>";
echo $row['sender'];
echo "</td><td>";
echo $row['msgText'];
echo "</td>";
?>
<td>
<form action="delete.php" method="post">
<input type="hidden" name="delete_id" value="<?php $_SESSION['id'] = $row['id']; ?>" />
<input type="submit" value="Delete" />
</form>
</td>
</tr>
<?php endwhile; ?>
also don't use $_SESSION['id'] while deleting the records. use $_POST['delete_id']

adjusting my code to take the user to the search results if there is any

this is the first form that in the header of the page which search my titles.
<form action="index.php?cat=search_results&learn_id=1" method="post">
<div id="topSearchBodyStyle">
<input type="text" name="search" class="topSearchTextBackground" />
</div>
<div id="topSearchButtonStyle">
<input type="submit" name="submit" class="topSearchButtonBackground" value="" />
</div>
</form>
and this is the page called searchPage.php
<?php
if (isset($_POST['search'])){
$getSearch = clean_text($_POST['search']);
$connectToDb = "select * from tutorials where tutorial_title like '%".$getSearch."%' and active=1";
$searchResults = $db->query($connectToDb) or die($db->error);
$numResultas = $searchResults ->num_rows;
echo "<p class='counter_search'>Found : " . $numResultas . "</p>";
switch ($numResultas) {
case 0:
include "searchPageAdvanced.php";
break;
case $numResultas >= 1:
while($row = mysqli_fetch_array($searchResults)) {
echo "<a class='counter_linkHeader' href='index.php?cat=tutorials_view&learn_id=5&tutorial_id=".$row['tutorial_id']."'>".$row['tutorial_title']."</a>";
echo "<p class='counter_description'>";
$your_desired_width=200;
$description=$row['content'];
if (strlen($description) > $your_desired_width) {$description = wordwrap($description, $your_desired_width); $description = substr($description, 0, strpos($description, "\n"))." ..."; } echo $description;
echo"</p>";
}
break;
}
}else{
?>
<p> </p>
<table width="875" border="0">
<tr>
<td align="center" valign="middle"><img src="http://bytes.com/images/searchError.jpg" width="223" height="147" alt="search error" /></td>
</tr>
<tr>
<td align="center" valign="middle">Sorry you came here by mistake <br />
please use the search box to get results</td>
</tr>
</table>
<p> </p>
<?php
}
?>
and the is the advanced search page.
which will search the content.
<form action="" method="post">
<input type='text' name='searchAdv' />
<input type='submit' name='submit_adv' value='Search' id="submit_adv" />
</form>
</td>
</tr>
<tr>
<td align='center' valign='middle'><p>Sorry you came here because your search didn't </p>
<p>meet any of the content try advanced!!</p></td>
</tr>
</table>
<?php
if (isset($_POST['submit_adv'])){
$getSearch = clean_text($_POST['searchAdv']);
$connectToDb = "select * from tutorials where content like '%".$getSearch."%' and active=1";
$searchResultsAdv = $db->query($connectToDb) or die($db->error);
while($rowAdv = mysqli_fetch_array($searchResultsAdv)) {
echo "<a class='counter_linkHeader' href='index.php?cat=tutorials_view&learn_id=5&tutorial_id=".$rowAdv['tutorial_id']."'>".$rowAdv['tutorial_title']."</a>";
echo "<p class='counter_description'>";
$your_desired_width=200;
$description=$rowAdv['content'];
if (strlen($description) > $your_desired_width) {$description = wordwrap($description, $your_desired_width); $description = substr($description, 0, strpos($description, "\n"))." ..."; } echo $description;
echo"</p>";
}
}
?>
now again the problem begin in the advanced search page, the search page is working fine
but when I search in the advanced page it return the page empty like he didn't take any thing for the input area SearchAdv

php function call messes up table

I've got a html table I build from the database:
<tr onclick="DoNav('<?php echo $result_videos[$i]["video_url"]; ?>');">
<td>
<?php echo $result_videos[$i]["camera_name"]; ?>
</td>
<td>
Timezone: <?php echo queryTimezone(); ?> <br>
Video Size: <?php echo $result_videos[$i]["video_size"]; ?> bytes <br>
Video Length: <?php echo strTime($result_videos[$i]["video_length"]); ?>
</td>
<td>
<form name="myform" action="<?php echo htmlentities($_SERVER['REQUEST_URI']); ?>" method="POST">
<input type="submit" name="delete_video" value="Delete" title="Delete this video" onClick="return confirm('Are you sure you want to delete?')"/>
<input type="hidden" name="video_url" value="<?php echo $result_videos[$i]["video_url"]; ?>" />
</form>
</td>
</tr>
The problem is this function:
function queryTimezone()
{
$query = "SELECT timezone FROM #__camcloud_users WHERE user_id=".$user->id;
$db->setQuery($query);
$timezone = $db->loadResult();
return $timezone;
}
It messes the table up. I don't seem to get any php errors and it cuts off the table at the "Timezone:" part and throws it to the top right of the page. Basically where I call the function queryTimezone. If I change to put this inside the html table it works fine:
<tr onclick="DoNav('<?php echo $result_videos[$i]["video_url"]; ?>');">
<td>
<?php echo $result_videos[$i]["camera_name"]; ?>
</td>
<td>
Timezone: <?php
$query = "SELECT timezone FROM #__camcloud_users WHERE user_id=".$user->id;
$db->setQuery($query);
$timezone = $db->loadResult();
echo $timezone;
?> <br>
Video Size: <?php echo $result_videos[$i]["video_size"]; ?> bytes <br>
Video Length: <?php echo strTime($result_videos[$i]["video_length"]); ?>
</td>
<td>
<form name="myform" action="<?php echo htmlentities($_SERVER['REQUEST_URI']); ?>" method="POST">
<input type="submit" name="delete_video" value="Delete" title="Delete this video" onClick="return confirm('Are you sure you want to delete?')"/>
<input type="hidden" name="video_url" value="<?php echo $result_videos[$i]["video_url"]; ?>" />
</form>
</td>
</tr>
This works fine. Did I do something wrong with how I call the function?
The function cannot determine what $user->id, therefore doesnt return a valid result... Theres nothing in the function that defines what $user is
Use his function declaration instead:
function queryTimezone($user,$db)
{
$query = "SELECT timezone FROM #__camcloud_users WHERE user_id=".$user->id;
$db->setQuery($query);
$timezone = $db->loadResult();
return $timezone;
}
call this way:
Timezone: <?php echo queryTimezone($user,$db); ?> <br>

Categories