In my project I have done a pagination using PHP, I have done it as follows:
Each buttons(NEXT PAGE and PREVIOUS PAGE) are hyperlinks which links to the same page with passing a GET variable (PAGENUMBER). For each page change, there are scripts for
connect to DB .
query for the data for the specified page.
close the
DB connection. displays the data.
The problem is that it is working slowly. Is there any alternative method for each time connect to db and query for the data and close db connection.
Also During the pagination I want to reload only the datas from DB and all other contents in page remains the same and dont want to reload. How to achieve this?
The script is given below
<?php
require_once("./include/membersite_config.php"); //include files for login system
if($fgmembersite->CheckLogin())
{
$login=true;
}
else
{
$login=false;
}
require_once("db.php");
$con=connect(); //connect to db and select the db
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<HTML>
<HEAD>
<TITLE> Gallery </TITLE>
<META name="generator" content="Adobe Photoshop(R) CS Web Photo Gallery">
<META http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
<link href="images/galleryStyle.css" rel="stylesheet" type="text/css">
<link rel="STYLESHEET" type="text/css" href="style/new.css" />
</HEAD>
<body marginheight=0 marginwidth=0 leftmargin=0 topmargin=0>
<table><tr>
<?php
//////////////////DISPLAYING IMAGE THUNBNAILS//////////////////////
$query="SELECT COUNT(*) FROM gallery ";
$res = query($query);
$raw=mysql_fetch_array($res);
$imagecount=$raw[0];
if($imagecount==0) { die ("No images found"); }
$pagecount=ceil($imagecount/15);
$page = isset($_GET['page']) ? mysql_real_escape_string($_GET['page']) : 1;
if (isset($_GET['page']))
{
if (!(ctype_digit($_GET['page']) and $_GET['page']>0 and $_GET['page']<=$pagecount))
{
die ("You are not autorised to viw this page");
}
}
$start= ($page*15)-15;
$query = "SELECT * FROM gallery ORDER BY imageid DESC LIMIT $start , 15";
$res = query($query);
$count= mysql_num_rows($res);
$index=0;
for($i=1;$i<=3;$i++)
{
?>
<TR>
<?php
for($j=1;$j<=5;$j++)
{
if(!$raw=mysql_fetch_array($res)) {break;}
$index++;
$imageid=$raw['imageid'];
$thumbpath= $raw['thumbpath'];
$largepath=$raw['largepath'];
$caption=$raw['caption'];
?>
<A name=1 href="image.php?imageid=<?php echo $imageid ?>&imageindex=<?php echo ((($page-1)*15)+$index-1) ; ?> "><IMG border=0 src="<?php echo $thumbpath; ?>" height="75" width="75" alt="<?php echo $caption ?>" title="<?php echo $caption ?>" ></A><BR>
<?php
echo "<a href='delete.php?delete=yes&imageid=".$imageid.'&page='.$page."'>Delete </a>"
echo "<a href='replace.php?update=yes&imageid=".$imageid.'&page='.$page."'>Replace </a>"
?>
</table>
</td>
<?php } ?>
</TR>
<?php
}
if ($page!=1)
{
?>
<td width=17><IMG SRC="images/previous.gif" BORDER=0></td>
<?php } ?>
<td align=middle class="pagenums"><?php echo "page ".$page." of ".$pagecount ?></td>
<?php
if ($page!=$pagecount)
{
?>
<td align=right width=17><img border=0 src="images/next.gif"></td>
<?php } ?>
</table>
</body>
</html>
There are lot much options available
go with javascript pagination
ajax pagination
try to reduce pagination code(optimized code)
You do not need to connect/close db for each page change
use the ajax script for connecting and getting database values with reloading the current page you can do it -- -- -- --- -- -- try ajax
Related
Good afternoon all :)
I would like to display my MySQL output on a PHP page as rows rather than columns for easier mobile viewing and scrolling (so the user can just scroll down the data instead of across).
I'd read about pivots and transposing but wasn't sure what was the most appropriate way to transform the return data output on the webpage. Please can you advise on what is best to use? It looks like it's easier to do it in PHP rather than MySQL?
I'm using a standard post form, connection PDO, isset, thead, php echo td and th etc.
My current code:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<meta http-equiv="x-ua-compatible" content="ie=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<title></title>
<link rel="stylesheet" href="css/style.css" />
</head>
<body>
<h1>Find people</h1>
<form method="post">
<label for="people">Enter person</label>
<input type="text" id="people" name="people">
<input type="submit" name="submit" value="View Results">
</form>
<?php
//error_reporting(-1);
//ini_set('display_errors', 'On');
if (isset($_POST['submit'])) {
try {
require "./config.php";
require "./common.php";
$connection = new PDO($dsn, $username, $password, $options);
$sql = "SELECT *
FROM Basics
WHERE UniqueID = :people";
$people = $_POST['people'];
$statement = $connection->prepare($sql);
$statement->bindParam(':people', $people, PDO::PARAM_STR);
$statement->execute();
$result = $statement->fetchAll();
} catch(PDOException $error) {
echo $sql . "<br>" . $error->getMessage();
}
}
?>
<?php
if (isset($_POST['submit'])) {
if ($result && $statement->rowCount() > 0) { ?>
<h2>Results</h2>
<table>
<?php echo '<table border="1">';?>
<thead>
<tr>
<th>Field 1</th>
<th>Field 2</th>
<th>Field 3</th>
</tr>
</thead>
<tbody>
<?php foreach ($result as $row) { ?>
<tr>
<td><?php echo escape($row["Field 1"]); ?></td>
<td><?php echo escape($row["Field 2"]); ?></td>
<td><?php echo escape($row["Field 3"]); ?></td>
</tr>
<?php } ?>
</tbody>
</table>
<?php } else { ?>
<br>No results found for <?php echo escape($_POST['people']); ?>, as the data has likely not been added yet.
<?php }
} ?>
<!--
<?php if (isset($_POST['submit']) && $statement) { ?>
<?php echo escape($_POST['people']); ?> successfully found.
<?php } ?>
-->
</body>
</html>
My current output:
Current example output:
Output example I would like:
Similar to this example I found (can be in a table or not like below):
Update edit:
Looks like I just needed to use ul and li!
<ul>
<li><b>Name:</b> <?php echo escape($row["Name"]); ?></li>
</ul>
I would use array_walk() to loop over the rows and within that loop, start the tr-tag, loop over the values of the current row, output them as td-elements, exit the td-loop, output the closing tr-tag and exit the tr-loop. Not that fancy solution but simple.
Looks like I just needed to use ul and li!
<ul>
<li><b>Name:</b> <?php echo escape($row["Name"]); ?></li>
</ul>
I am trying to link through to the single row record information in my mysql database from my search using php/ajax_pagination and the code that I am trying to get to work is:
<div id="posts_content">
<?php
//Include pagination class file
include('Pagination.php');
//Include database configuration file
include('dbConfig.php');
$limit = 3;
//get number of rows
$queryNum = $db->query("SELECT COUNT(*) as postNum FROM posts");
$resultNum = $queryNum->fetch_assoc();
$rowCount = $resultNum['postNum'];
//initialize pagination class
$pagConfig = array(
'totalRows' => $rowCount,
'perPage' => $limit,
'link_func' => 'searchFilter'
);
$pagination = new Pagination($pagConfig);
//get rows
$query = $db->query("SELECT * FROM posts ORDER BY id DESC LIMIT $limit");
if($query->num_rows > 0){ ?>
<div class="posts_list">
<?php
while($row = $query->fetch_assoc()){
$postID = $row['id'];
?>
<div class="list_item"><h2><?php echo $row["title"]; ?></h2></div>
<?php } ?>
</div>
<?php echo $pagination->createLinks(); ?>
<?php } ?>
</div>
There is obviously something wrong with my href link:
<h2><?php echo $row["title"]; ?></h2>
OR my file.php page:
<?php
// GET ID FROM THE URL
$id = $_GET['id'];
?>
<!DOCTYPE HTML>
<html lang="en">
<head>
<title>Ajax Pagination with Search and Filter in PHP</title>
<link href='style.css' rel='stylesheet' type='text/css'>
<script src="jquery.min.js"></script>
<script type="text/javascript"></script>
</head>
<body>
<?php
$sql =mysql_query("select * from posts where id='".$id."'");
while($row = mysql_fetch_array($sql)){
?>
<tr>
<th>title:</th>
<th>created:</th>
<th>modified:</th>
<th>statusr:</th>
</tr>
<tr>
<td><?=$row['title']?></td>
<td><?=$row['created']?></td>
<td><?=$row['modified']?></td>
<td><?=$row['status']?></td>
</tr>
<?php
}
?>
But I cannot understand why as everything else seems to be working fine, maybe I have been looking at this to long and missed something blatently obvious... but any help would be greatly appreciated.
Use Below Code:
<div class="list_item"><h2><?php echo $row["title"]; ?></h2></div>
This is my "config.php" file:
<?php
/******************************************************
------------------Required Configuration---------------
Please edit the following variables so the forum can
work correctly.
******************************************************/
//We log to the DataBase
mysql_connect('', '', '');
mysql_select_db('');
//Username of the Administrators
$admin='Hexagon';
$mod='test1';
/******************************************************
-----------------Optional Configuration----------------
******************************************************/
//Forum Home Page
$url_home = 'index.php';
//Design Name
$design = 'default';
/******************************************************
----------------------Initialization-------------------
******************************************************/
include('init.php');
?>
and this is my "delete_topic.php" file:
<?php
//This page let delete a topic
include('config.php');
if(isset($_GET['id']))
{
$id = intval($_GET['id']);
if(isset($_SESSION['username']))
{
$dn1 = mysql_fetch_array(mysql_query('select count(t.id) as nb1, t.title, t.parent, c.name from topics as t, categories as c where t.id="'.$id.'" and t.id2=1 and c.id=t.parent group by t.id'));
if($dn1['nb1']>0)
{
if($_SESSION['username']==$admin)
if($_SESSION['username']==$mod)
{
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<link href="<?php echo $design; ?>/style.css" rel="stylesheet" title="Style" />
<title>Delete a topic - <?php echo htmlentities($dn1['title'], ENT_QUOTES, 'UTF-8'); ?> - <?php echo htmlentities($dn1['name'], ENT_QUOTES, 'UTF-8'); ?> - Forum</title>
</head>
<body>
<div class="header">
<img src="<?php echo $design; ?>/images/logo.png" alt="Forum" />
</div>
<div class="content">
<?php
$nb_new_pm = mysql_fetch_array(mysql_query('select count(*) as nb_new_pm from pm where ((user1="'.$_SESSION['userid'].'" and user1read="no") or (user2="'.$_SESSION['userid'].'" and user2read="no")) and id2="1"'));
$nb_new_pm = $nb_new_pm['nb_new_pm'];
?>
<div class="box">
<div class="box_left">
Forum Index > <?php echo htmlentities($dn1['name'], ENT_QUOTES, 'UTF-8'); ?> > <?php echo htmlentities($dn1['title'], ENT_QUOTES, 'UTF-8'); ?> > Delete the topic
</div>
<div class="box_right">
Your messages(<?php echo $nb_new_pm; ?>) - <?php echo htmlentities($_SESSION['username'], ENT_QUOTES, 'UTF-8'); ?> (Logout)
</div>
<div class="clean"></div>
</div>
<?php
if(isset($_POST['confirm']))
{
if(mysql_query('delete from topics where id="'.$id.'"'))
{
?>
<div class="message">The topic have successfully been deleted.<br />
Go to "<?php echo htmlentities($dn1['name'], ENT_QUOTES, 'UTF-8'); ?>"</div>
<?php
}
else
{
echo 'An error occured while deleting the topic.';
}
}
else
{
?>
<form action="delete_topic.php?id=<?php echo $id; ?>" method="post">
Are you sure you want to delete this topic?
<input type="hidden" name="confirm" value="true" />
<input type="submit" value="Yes" /> <input type="button" value="No" onclick="javascript:history.go(-1);" />
</form>
<?php
}
?>
</div>
<div class="foot">Simple PHP Forum Script - Webestools</div>
</body>
</html>
<?php
}
else
{
echo '<h2>You don\'t have the right to delete this topic.</h2>';
}
}
else
{
echo '<h2>The topic you want to delete doesn\'t exist.</h2>';
}
}
else
{
echo '<h2>You must be logged as an administrator to access this page: Login - Sign Up</h2>';
}
}
else
{
echo '<h2>The ID of the topic you want to delete is not defined.</h2>';
}
?>
yet for some reason anyone in the $mod group cannot delete topics. This has been irking me for some time, as I need moderators to be able to delete topics, and edit posts, but they can't even delete the topic. Any suggestions? This is a really big project I'm working on and it is important to me that I can have mods AND admins as to differ between the two. [btw, the database info is filled out in MY config.php file]
A good way to sort this problem out, is to make a field in your users ( or members) table and call this field "user_levels", where set the Admin as 1, Moderator as 2, other members as 3 or empty or 0 (whatever you like).Than you can set a session $_SESSION['user_levels'] and always check against that session as follows
if ($_SESSION['user_levels']==1 || $_SESSION['user_levels']==2)
{
// Grant him permission to delete the record
}
else
{
// tell him that he is not authorize to delete it
}
Your problem is here..
if($_SESSION['username']==$admin)
if($_SESSION['username']==$mod)
{
What's happening is if the $admin conditional is not satisfied, you're finding yourself out of the block that allows deleting... I think you may want this instead
if($_SESSION['username']==$mod || $_SESSION['username']==$admin)
{
Also please start using mysqli as mysql is deprecated.
I want to show a picture in my code but for some reason I get a big white almost blank page with a broken link img. I want to show the image and along with any other information.
I also want to resize the image(so it doesnt cover the whole page).
The code:
<?php
session_start()
?>
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<meta name="viewport" content="initial-scale=1.0" />
<link rel="stylesheet" href="css/style.css" />
</head>
<div id="Container">
<div id="header">
<h1>Welcome!</h1>
</div>
<div id="navigation">
<?php
include_once "navigation.php";
?>
</div>
<div id="Content">
<?php
if (isset($_GET['search'])) {
$Name = $_GET['search'];
mysql_connect("localhost","root","") or die ("Could not connect to the server!");
mysql_select_db("pictures") or die ("That database could not be found!");
$query = mysql_query("SELECT * FROM picture WHERE Name='$Name'") or die ("The query could not be completed, please try again later!");
if (mysql_num_rows($wepquery) !=1) {
die ("That name could not be found!");
}
while ($row = mysql_fetch_array($query, MYSQL_ASSOC, 0)) {
$dbName = $row['Name'];
$dbCreator = $row['Creator'];
$dbDescription = $row['Description'];
$imageData = $row['Image'];
}
header("Content-type: image/jpeg");
if($Name != $dbName) {
die ("There has been a fatal error. Please try again.");
}
?>
<h2><?php echo $Name; ?></h2>
<br />
<table>
<tr><td>Creator: <?php echo $dbCreator;?></td></tr>
<tr><td>Description:<br /><?php echo $dbDescription;?></td></tr>
<tr><td>Picture:<br /><?php echo $imageData;?></td></tr>
</table>
<?php
} else die ("You need to specify a submission!");
?>
</div>
</div>
</html>
The database:
id, Name, Creator, Description, Image_name, Image(mediumblob).
The last two fields as you can see is dedicated to pictures. Yes I know about PDO and MySQLi, but I just want to finish this code first. Any help?
Images need to either be served by URL or the blob needs to be converted to a data URI like so:
<table>
<tr><td>Creator: <?php echo $dbCreator;?></td></tr>
<tr><td>Description:<br /><?php echo $dbDescription;?></td></tr>
<tr><td>Picture:<br /><?php echo "<img src='data:image/jpeg;base64," . base64_encode( $imageData ) . "' />"; ?></td></tr>
</table>
if you want image you need to enclose it with image tags. assume if your $imageData contains the location of the image then you can do the following.
<img src='<?php echo $imageData;?>' ... />
if your $imageData contains actual binary data of an image you need to create a separate call to a php script to return the imageData. and make the call to be the src attribute of an img tag.
is your path exactly pointing toward the image? have checked "../../" ? another question, is your image really inside an image tag? there must be something like this:
<img src="<?php echo $imagePath; ? />
So I'm trying to make a page where i can display results from my database table. You should be able to search and there should be some pagination as there are thousands of results.
I've managed to make a page which just has the search, and works perfect. So now i need to know how would would integrate some pagination into that.
index.php
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title></title>
</head>
<body>
<div id="container">
<form action="" method="get">
<input type="text" name="search" id="search" placeholder="Search" />
<input type="submit" />
</form>
<?php include 'process.php'; ?>
</div> <!-- /container -->
<script src="js/jquery.js"></script>
<script src="js/script.js"></script>
</body>
</html>
process.php
<?php include 'dbconfig.php'; ?>
<?php include 'connect.php'; ?>
<?php
$search = $_GET['search'];
$result = mysql_query("SELECT * FROM oantkb WHERE Name LIKE '%$search%' ORDER BY `INDEX` DESC");
echo '<table class="table">';
echo '<thead>';
echo '<tr>';
echo '<th>#</th>';
echo '<th>Pic</th>';
echo '<th>Name</th>';
echo '</tr>';
echo '</thead>';
echo '<tbody>';
while($row = mysql_fetch_assoc($result)) {
$pic = $row['Pic'];
$name = $row['Name'];
echo '<tr>';
echo '<td>#</td>';
echo '<td><img src="'.$pic.'" height="50" width 50"></td>';
echo '<td>'.$name.'</td>';
echo '</tr>';
}
echo '</tbody>';
echo '</table>';
?>
Right now it works like it should. When i search it will say index.php?search=banana, but i need some pagination added so it will say for example index.php?search=banana&?page=2. Or something along those lines. Hope it makes sense...i'm a php newb :)
Include at the end of your sql query the following:
$resultsPerPage=10;
$page = ($_GET["page"]-1)*$resultsPerPage;
$query = $query." LIMIT $page,$resultsPerPage";
mysql_query($query);
By the way the mysql_ library is deprecated in favor of mysqli.
Also the above is susceptible to sql injection attacks because $_GET["page"] isn't first sanitized, but for simplicity I did it this way.
This assumes a paging scheme that starts at 1.
i've been using Pear Pagination for a long time. you can try it.
here is a good tutorial for setting it up
Simple Pagination in PHP tutorial
a good thing to add is clean your variable before using them in your query.