<?php
require('db_info.php');
$recordsPerPage = 5;
if (isset($_GET['page']))
$curPage = $_GET['page'];
else
$curPage = 1;
$startIndex = ($curPage-1) * $recordsPerPage;
try {
$pdoObject = new PDO("mysql:host=$dbhost; dbname=$dbname;", $dbuser, $dbpass);
$sql = "SELECT count(id) FROM usercom";
$statement = $pdoObject->query($sql);
$record = $statement->fetch(PDO::FETCH_ASSOC);
$pages = ceil($record['count(id)']/$recordsPerPage);
$record=null;
$sql = "SELECT * FROM usercom LIMIT $startIndex, $recordsPerPage ORDER BY date DESC";
$statement = $pdoObject->query($sql);
while ( $record = $statement->fetch(PDO::FETCH_ASSOC) ) {
echo '<p>'.$record['date'].'<br/>'.$record['userComment'].'<br/>';
}
$statement->closeCursor();
$pdoObject = null;
} catch (PDOException $e) {
echo 'PDO Exception: '.$e->getMessage();
die();
}?></p>
I'm trying to fetch result from a database and use pagination. The problem is that the descending order asked in the statement never applies. Why isn't this working? If I don't add the line "ORDER BY date DESC" it works just fine, but when I do it prints error that I'm trying to fetch a non-object.
Your syntax isn't quite correct,
Use this one instead,
$sql = "SELECT * FROM `usercom` ORDER BY `date` DESC LIMIT $startIndex, $recordsPerPage";
Related
I have written a paging script to page all the posts in my blog. Now I would like to create and endpoint such that I can go to mydomain/index.php?blogID1, mydomain/index.php?blogID2, mydomain/index.php?blogID3, mydomain/index.php?blogID4, etc.
Where can I read about doing this, and how do I implement it the easiest way possible, given my current script:
<?php
$rowsPerPage = 2;
try
{
$conn = new PDO( "sqlsrv:server=localhost ; Database=blog", "******", "*******");
$conn->setAttribute( PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION );
}
catch(Exception $e)
{
die( print_r( $e->getMessage() ) );
}
try
{
$tsql = "SELECT COUNT(blogID) FROM blog_posts";
$stmt = $conn->query($tsql);
$rowsReturned = $stmt->fetch(PDO::FETCH_NUM);
if($rowsReturned[0] == 0)
{
echo "No rows returned.";
}
else
{
$numOfPages = ceil($rowsReturned[0]/$rowsPerPage);
for($i = 1; $i<=$numOfPages; $i++)
{
$pageNum = "index.php?pageNum=$i";
print("<a href='$pageNum' class='btn btn-primary active btn-sm'>$i</a> ");
}
}
$tsql = "SELECT * FROM
(SELECT ROW_NUMBER() OVER(ORDER BY blogID DESC)
AS RowNumber,
blog_title,
blog_post,
blog_author,
blog_category,
blog_date,
blogID
FROM blog_posts)
AS Temp
WHERE RowNumber BETWEEN ? AND ?";
$stmt2 = $conn->prepare($tsql);
if(isset($_GET['pageNum']))
{
$highRowNum = $_GET['pageNum'] * $rowsPerPage;
$lowRowNum = $highRowNum - $rowsPerPage + 1;
}
else
{
$lowRowNum = 1;
$highRowNum = $rowsPerPage;
}
$params = array(&$lowRowNum, &$highRowNum);
$stmt2->execute(array($lowRowNum, $highRowNum));
while($row = $stmt2->fetch(PDO::FETCH_NUM) )
{
echo "$row[1]";
echo "$row[2]";
echo "$row[3]";
echo date_format( new DateTime($row['5']), 'd M Y, H:i' );
echo "$row[4]";
echo "$row[6]";
}
}
catch(Exception $e)
{
die( print_r( $e->getMessage() ) );
}
?>
Is row a post?
You can order your rows by any column, then limit the number of results and set an offset depending which page was requested.
Here's about mysql that endpoint: MySQL Data - Best way to implement paging?
For example if page is requested like this: index.php?pageNum=15 and you are showing 5 posts per page,
Grab that value with $page = $_GET['pageNum'] and set your PDO prepared statements for result number and offset (LIMIT).
Declare $resultsPerPage = 5
SELECT *
FROM Posts
LIMIT :offset, :maxResults
And push in those prepared statements:
offset --> ($page - 1) * $resultsPerPage
maxResults --> $resultsPerPage
I'm having a hard time getting this search results with pagination code to work. It does successfully grab the search keyword entered in the html form on another page and brings it into this search.php page. if I echo $search I see the keyword on the page. But I get no results even though I should for the query. Can anyone see what might be going on?
require "PDO_Pagination.php";
if(isset($_REQUEST["search_text"]) && $_REQUEST["search_text"] != "")
{
$search = htmlspecialchars($_REQUEST["search_text"]);
$pagination->param = "&search=$search";
echo $search;
$pagination->rowCount("SELECT * FROM stories WHERE stories.genre = $search");
$pagination->config(3, 5);
$sql = "SELECT * FROM stories WHERE stories.genre = $search ORDER BY SID ASC LIMIT $pagination->start_row, $pagination->max_rows";
$query = $connection->prepare($sql);
$query->execute();
$model = array();
while($rows = $query->fetch())
{
$model[] = $rows;
}
}
else
{
$pagination->rowCount("SELECT * FROM stories");
$pagination->config(3, 5);
$sql = "SELECT * FROM stories ORDER BY SID ASC LIMIT $pagination->start_row, $pagination->max_rows";
$query = $connection->prepare($sql);
$query->execute();
$model = array();
while($rows = $query->fetch())
{
$model[] = $rows;
}
}
$query = "SELECT * FROM stories";
if(isset($_REQUEST["search_text"]) && $_REQUEST["search_text"] != "")
{
$search = htmlspecialchars($_REQUEST["search_text"]);
$pagination->param = "&search=$search";
$query .= " WHERE genre LIKE '%$search%'";
}
// No need for else statement.
$pagination->rowCount($query);
$pagination->config(3, 5);
$query .= " ORDER BY SID ASC LIMIT {$pagination->start_row}, {$pagination->max_rows}";
$stmt = $connection->prepare($query);
$stmt->execute();
$model = $stmt->fetchAll();
var_dump($model);
In your query do:
WHERE stories.genre LIKE '%string%');
instead of:
WHERE stories.genre = 'string');
Because the equals will want to literally equal the field.
I'm using to following to count the number of rows in a table:
// Count rows
$sql = "SELECT COUNT(*) FROM articles";
$result = mysqli_query($con,$sql);
$max = mysqli_fetch_row($result);
echo $max;
This echoes array. I understand why but I can't find how to get the value in this case. I've tried $max[0]. I don't understand how to reference the column in the array in this case.
try this:
$sql = "SELECT COUNT(*) as counts FROM articles";
$result = mysqli_query($con,$sql);
$max = mysqli_fetch_assoc($result);
echo $max['counts'];
some docs here
EDIT:
$sql = "SELECT COUNT(*) as counts FROM articles";
$result = mysqli_query($con,$sql);
while($max = mysqli_fetch_assoc($result))
{
echo $max['counts'];
}
You should use MySQL PDO.
Try this:
try{
$conn = new PDO("mysql:host=localhost;dbname=dbname", username, password);
$conn -> setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
} catch(PDOException $e) {
$errors = "There is no connection to the Server: localhost";
}
$qry = $conn -> prepare("SELECT COUNT(*) AS counts FROM articles");
$qry -> execute();
while($row = $qry->fetch(PDO::FETCH_ASSOC)) {
$Total = $row['counts'];
}
echo $Total;
I have multiple record(s) in PHPMYADMIN and now i am trying to fetch those record(s) using PHP Code, but always i am getting Array ( ) 1 whenever i run my php script using Localhost, however i have 5 rows in table.
Please see below code:
<?php
$objConnect = mysql_connect("localhost","root","");
$objDB = mysql_select_db("mydatabase");
$strMemberID = $_POST["sMemberID"];
$strSQL = "SELECT * FROM order_details WHERE
MemberID = '".mysql_real_escape_string($strMemberID)."' ORDER BY OrderID DESC ";
$objQuery = mysql_query($strSQL);
while($obResult = mysql_fetch_assoc($objQuery))
{
$arr = array();
$arr["OrderID"] = $obResult["OrderID"];
$arr["ItemDetails"] = $obResult["ItemDetails"];
}
mysql_close($objConnect);
echo print_r($arr);
?>
change your code in while loop.
declare $arr outside the loop. declaring array inside loop will clear it before initializing. thats why you are getting a single row in each run.
$arr = array();
while($obResult = mysql_fetch_assoc($objQuery))
{
$arr["OrderID"] = $obResult["OrderID"];
$arr["ItemDetails"] = $obResult["ItemDetails"];
}
Also, to view array elements use echo json_encode($arr) or var_dump($arr) or print_r($arr);
it will definitely work for you
It's not directly an answer to your question but while you're at it try to use PDO and prepared statements
$strMemberID = $_POST["sMemberID"];
$strSQL = 'SELECT * FROM order_details WHERE MemberID = ? ORDER BY OrderID DESC';
try {
$db = new PDO('mysql:host=localhost;dbname=dbname;charset=UTF8', 'user', 'password');
$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$db->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);
$query = $db->prepare($strSQL);
$query->execute(array($strMemberID));
$result = $query->fetchAll(PDO::FETCH_ASSOC);
} catch (PDOException $e) {
echo 'Exeption: ' .$e->getMessage();
$result = false;
}
$query = null;
$db = null;
var_dump($result);
You may like it.
I want to create a function so that I won't repeat myself.
This is my current code
<?php
$targetpage = "index.php";
$limit = 20;
$sql1 = $db->prepare("SELECT * FROM classified ORDER BY date DESC");
/*** fetch Number of results ***/
$total_pages =$sql1->rowCount();
$stages = 3;
$page = ($_GET['page']);
if($page){
$start = ($page - 1) * $limit;
}else{
$start = 0;
}
$sql = $db->prepare("SELECT * FROM classified ORDER BY date DESC LIMIT $start,
$limit ")or die(print_r($sql->errorInfo(), true));
$sql->execute();
$result = $sql->fetchAll();
//Include pagination
require_once("pagination.php");
// pagination
echo $paginate;
foreach($result as $row){
$id = htmlentities($row['id'], ENT_QUOTES);
$id_city = htmlentities($row['id_city'], ENT_QUOTES);
$title = htmlentities($row['title'], ENT_QUOTES ,'utf-8');
$querya = $db->prepare("SELECT * FROM city WHERE id = :id_city");
/*** bind the paramaters ***/
$querya->bindParam(':id_city', $id_city, PDO::PARAM_INT);
/*** execute the prepared statement ***/
$querya->execute();
/*** fetch the results ***/
$resultya = $querya->fetchAll();
foreach($resultya as $rowa)
{
$city_name = htmlentities($rowa['city'], ENT_QUOTES, 'utf-8');
}
}
?>
Now I have another file that uses the same code except it has a condition when retrieving data from database.
So instead of:
$sql1 = $db->prepare("SELECT * FROM classified ORDER BY date DESC");
$sql = $db->prepare("SELECT * FROM classified ORDER BY date DESC LIMIT $start,
$limit ")or die(print_r($sql->errorInfo(), true));
The other file:
$sql1 = $db->prepare("SELECT * FROM classified where type = '1' ORDER BY date DESC");
$sql = $db->prepare("SELECT * FROM classified where type = '1' ORDER BY date DESC
LIMIT $start, $limit ")or die(print_r($sql->errorInfo(), true));
The difference is where type = 1
Is it possible to combine all this in one function?
Thanks
I added some notes into the code, does this make sense?
See below:
<?php
/*
$db - PDO object
$limit - number of listings to show on the page
$page - page to show
$where - the additional where condition to pass in
*/
function getItems($db=null,$limit=20,$page='',$where='') {
// check if $db exists before doing anything
if ($db) {
$sql1 = $db->prepare("SELECT * FROM classified ORDER BY date DESC");
/*** fetch Number of results ***/
$total_pages =$sql1->rowCount();
$stages = 3;
if($page){
$start = ($page - 1) * $limit;
}else{
$start = 0;
}
$sql = $db->prepare("SELECT * FROM classified $where ORDER BY date DESC LIMIT $start,
$limit ")or die(print_r($sql->errorInfo(), true));
$sql->execute();
$result = $sql->fetchAll();
} else {
// I return an empty array here so that if something should fail $result will still be populated with an array
return array();
}
}
$targetpage = "index.php";
$result = getItems($db,20,$_GET['page'],'where type = "1"');
//Include pagination
require_once("pagination.php");
// pagination
echo $paginate;
foreach($result as $row){
$id = htmlentities($row['id'], ENT_QUOTES);
$id_city = htmlentities($row['id_city'], ENT_QUOTES);
$title = htmlentities($row['title'], ENT_QUOTES ,'utf-8');
$querya = $db->prepare("SELECT * FROM city WHERE id = :id_city");
/*** bind the paramaters ***/
$querya->bindParam(':id_city', $id_city, PDO::PARAM_INT);
/*** execute the prepared statement ***/
$querya->execute();
/*** fetch the results ***/
$resultya = $querya->fetchAll();
foreach ($resultya as $rowa) {
$city_name = htmlentities($rowa['city'], ENT_QUOTES, 'utf-8');
}
}
?>
Yes. Have one file and either send a POST or GET to it that tells the page if type==1.
Example
if ($_GET['t']==1){ $type = "WHERE type = '1'"; }else{ $type = ""; }
$sql1 = $db->prepare("SELECT * FROM classified " . $type . " ORDER BY date DESC");
$sql = $db->prepare("SELECT * FROM classified " . $type . " ORDER BY date DESC
LIMIT $start, $limit ")or die(print_r($sql->errorInfo(), true));
If you call the page this is listed on with page.php?t=1, then it will put the where statement in there. If you just call page.php, it will not put anything there.