Paging and query string for individual post MsSQL & PHP - php

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

Related

how to sum table1 and table2 (simple sum)

How I can sum Table1 and Table2
If table1 have more than one entry status "0" and table2 also more than one entry status "0" then sum Table1 + Table2.
Example
Table1 have 3 entrys with status "0" and table2 have 2 entrys with status "0" then sum is 2
Like first table = 1 and second table = 1
And if table1 have entries and table2 doesnt have entries then sum is 1
and if Both doesnt have entries then sum is 0
I tryed this if statements:
require_once('../../function.php');
try{
$database = new Connection();
$db = $database->openConnection();
$status = 0;
$sql = "SELECT ( SELECT COUNT(*) FROM contact WHERE status = 0 ) AS contact, COUNT(*) AS ordr FROM orrdr WHERE status = :status";
$qry = $db->prepare($sql);
$qry -> bindParam(':status', $status, PDO::PARAM_INT);
$qry -> execute();
$count = $qry->fetchColumn();
} catch (PDOException $e) {
echo "There is some problem in connection: " . $e->getMessage();
}
if ($count['contact'] => 1 && $count['ordr'] => 1) {
echo "2";
} elseif (empty($count['contact']) && empty($count['ordr']) {
echo "0";
} elseif () {
# code...
}
This is counting for notifications.
Status 1 is readed notification and status 0 is not readed notification.
I didnt finish my statements because I know this is wrong way to do it.
You can use the following SQL:
SELECT SUM(x.cnt)
FROM (
SELECT IF(COUNT(*) > 0, 1, 0) AS cnt FROM contact WHERE status = 0
UNION ALL
SELECT IF(COUNT(*) > 0, 1, 0) FROM orrdr WHERE status = 0
)x
So you can use the following PHP code:
require_once('../../function.php');
try {
$database = new Connection();
$db = $database->openConnection();
$status = 0;
$sql = "SELECT SUM(x.cnt) FROM (SELECT IF(COUNT(*) > 0, 1, 0) AS cnt FROM contact WHERE status = :status UNION ALL SELECT IF(COUNT(*) > 0, 1, 0) FROM orrdr WHERE status = :status)x";
$qry = $db->prepare($sql);
$qry -> bindParam(':status', $status, PDO::PARAM_INT);
$qry -> execute();
$count = $qry->fetchColumn();
} catch (PDOException $e) {
echo "There is some problem in connection: " . $e->getMessage();
}
echo $count;
If you need to know the sums of both queries you can use the following:
require_once('../../function.php');
try {
$database = new Connection();
$db = $database->openConnection();
$status = 0;
$sql = "SELECT (SELECT COUNT(*) FROM contact WHERE status = :status) AS cnt_contact, (SELECT COUNT(*) FROM orrdr WHERE status = :status) AS cnt_orrdr";
$qry = $db->prepare($sql);
$qry -> bindParam(':status', $status, PDO::PARAM_INT);
$qry -> execute();
$count_contact = $qry->fetchColumn(0);
$count_orrdr = $qry->fetchColumn(1);
} catch (PDOException $e) {
echo "There is some problem in connection: " . $e->getMessage();
}
if ($cnt_contact >= 1 && $cnt_orrdr >= 1) {
echo "2"; //both available.
} elseif($cnt_contact >= 1 && $cnt_orrdr == 0) {
echo "1"; //only contact available.
} elseif ($cnt_orrdr >= 1 && $cnt_contact == 0) {
echo "1"; //only orrdr available.
} elseif ($cnt_orrdr == 0 && $cnt_contact == 0) (
echo "0"; //nothing available.
}
//simpler solution instead of "if" above:
//echo (($cnt_contact > 0 ? 1 : 0) + ($cnt_orrdr > 0 ? 1 : 0));

i wrote some code for fetch data from database ,in mysql code is working and in pdo it is not working

This is mysql connection coding, it is working fine
the same code i wrote with pdo connection,it is not working i'm new to php please help me to get out of this problem.
thanks in advance
<?php
error_reporting(0);
ini_set('max_execution_time', 600);
require_once 'config.php';
if(isset($_GET["nm_mask"]))
$nm_mask = $_GET['nm_mask'];
else
$nm_mask = "";
if(isset($_GET["cd_mask"]))
$cd_mask = $_GET['cd_mask'];
else
$cd_mask = "";
if(isset($_GET["func"]))
$func = $_GET['func'];
else
$func = "";
$where = "WHERE 1=1";
if($nm_mask!='')
$where.= " AND Login LIKE '$nm_mask%'";
if($cd_mask!='')
$where.= " AND Manager_Login LIKE '$cd_mask%'";
if($func!='')
$where.= " AND Function LIKE '$func%'";
$page = $_GET['page']; // get the requested page
$limit = $_GET['rows']; // get how many rows we want to have into the grid
$sidx = $_GET['sidx']; // get index row - i.e. user click to sort
$sord = $_GET['sord']; // get the direction
if(!$sidx) $sidx =1; // connect to the database
$result = mysqli_query("SELECT COUNT(*) AS count FROM EmpMasterTB ".$where);
$row = mysqli_fetch_array($result,MYSQLI_ASSOC);
$count = $row['count'];
if( $count >0 ) {
$total_pages = ceil($count/$limit);
} else {
$total_pages = 0;
}
if ($page > $total_pages) $page=$total_pages;
if ($limit<0) $limit = 0;
$start = $limit*$page - $limit; // do not put $limit*($page - 1)
if ($start<0) $start = 0;
$SQL = "SELECT * from EmpMasterTB ". $where ." ORDER BY $sidx $sord LIMIT $start , $limit";
$result = mysqli_query( $SQL ) or die("Couldn?t execute query.".mysqli_error());
$responce->page = $page;
$responce->total = $total_pages;
$responce->records = $count;
$i=0;
while($row = mysqli_fetch_array($result,MYSQLI_ASSOC)) {
$responce->rows[$i]['id']=$row[WeekNo].$row[Login];
$responce->rows[$i]['cell']=array($row['WeekNo'],$row['WeekBeginning'],$row['SITE'],$row['Name'],$row['WFH'],$row['Login'],$row['Manager_Login'],$row['Lead'],$row['Cost_center'],$row['Business_Title'],$row['Function'],$row['Workgroup'],$row['Login_time'],$row['ROLE'],$row['Secondary_Skill'],$row['Weekoff'],""); $i++;
}
echo json_encode($responce);
?>
PDO connection code
<?php
error_reporting(0);
ini_set('max_execution_time', 600);
require_once 'config.php';
if(isset($_GET["nm_mask"]))
$nm_mask = $_GET['nm_mask'];
else
$nm_mask = "";
if(isset($_GET["cd_mask"]))
$cd_mask = $_GET['cd_mask'];
else
$cd_mask = "";
if(isset($_GET["func"]))
$func = $_GET['func'];
else
$func = "";
$where = "WHERE 1=1";
if($nm_mask!='')
$where.= " AND Login LIKE '$nm_mask%'";
if($cd_mask!='')
$where.= " AND Manager_Login LIKE '$cd_mask%'";
if($func!='')
$where.= " AND Function LIKE '$func%'";
$page = $_GET['page']; // get the requested page
$limit = $_GET['rows']; // get how many rows we want to have into the grid
$sidx = $_GET['sidx']; // get index row - i.e. user click to sort
$sord = $_GET['sord']; // get the direction
if(!$sidx) $sidx =1; // connect to the database
$count = $dbh->exec("SELECT COUNT(*) AS count FROM EmpMasterTB ".$where);
if( $count >0 ) {
$total_pages = ceil($count/$limit);
} else {
$total_pages = 0;
}
if ($page > $total_pages) $page=$total_pages;
if ($limit<0) $limit = 0;
$start = $limit*$page - $limit; // do not put $limit*($page - 1)
if ($start<0) $start = 0;
$SQL = "SELECT * from EmpMasterTB ". $where ." ORDER BY $sidx $sord LIMIT $start , $limit"; /*** The SQL SELECT statement ***/
$stmt = $dbh->query($SQL); /*** fetch into an PDOStatement object ***/
$responce->page = $page;
$responce->total = $total_pages;
$responce->records = $count;
$i=0;
/*** echo number of columns ***/
$obj = $stmt->fetch(PDO::FETCH_OBJ);
/*** loop over the object directly ***/
{
$responce->rows[$i]['id']=$obj->WeekNo.$obj->Login;
$responce->rows[$i]['cell']=array($obj->WeekNo ,$obj->WeekBeginning ,$obj->SITE ,$obj->Name ,$obj->WFH ,$obj->Login ,$obj->Manager_Login ,$obj->Lead ,$obj->Cost_center ,$obj->Business_Title ,$obj->Function ,$obj->Workgroup ,$obj->Login_time ,$obj->ROLE ,$obj->Secondary_Skill ,$obj->Weekoff ); $i++;
}
echo json_encode($ );
?>
You have missed for loop and you didn't pass response in json_encode().
Please check my below code:
/*** echo number of columns ***/
$objs = $stmt->fetch(PDO::FETCH_OBJ);
/*** loop over the object directly ***/
foreach($objs as $obj)
{
$responce->rows[$i]['id']=$obj->WeekNo.$obj->Login;
$responce->rows[$i]['cell']=array($obj->WeekNo ,$obj->WeekBeginning ,$obj->SITE ,$obj->Name ,$obj->WFH ,$obj->Login ,$obj->Manager_Login ,$obj->Lead ,$obj->Cost_center ,$obj->Business_Title ,$obj->Function ,$obj->Workgroup ,$obj->Login_time ,$obj->ROLE ,$obj->Secondary_Skill ,$obj->Weekoff ); $i++;
}
echo json_encode($responce );

PDO Sql statement order by error

<?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";

mysqli setting next and previous button using id

I would like to make a previous and next button to scroll through the database using ID. This is my code when I am still using mysql. Right now it is changed to mysqli so I have no idea whether this code still works or not, because I keep getting null.
function getNavID($id) {
$result4= mysqli_query("SELECT
( SELECT id FROM products_list
WHERE id > '$id' LIMIT 1 ) AS nextValue,
( SELECT id FROM products_list
WHERE id < '$id' ORDER BY id DESC LIMIT 1 ) AS prevValue
FROM products_list
LIMIT 1");
if ($resultID = mysqli_fetch_array($result4)) {
return $resultID;
}
else {
return NULL;
}
}
$LinkID = getNavID($id);
if (!is_null($LinkID['prevValue']))
{
?>
Previous
<?php
}
else if (!is_null($LinkID['nextValue']))
{
?>
Next
<?php
}
else
{
echo "No Entries";
}
Besides changing mysql_query to mysqli_query, is there anything that I need to change too? Thanks in advance for the help!
try this :
global $pdo;
$id = $the_selected_id;
$stmt_a = $pdo->prepare("
(SELECT * FROM images WHERE id < ? ORDER BY id DESC LIMIT 1)
UNION (SELECT * FROM images WHERE id = (SELECT MAX(id) FROM images)) LIMIT 1");
$stmt_b = $pdo->prepare("
(SELECT * FROM images WHERE id > ? ORDER BY id ASC LIMIT 1)
UNION (SELECT * FROM images WHERE id = (SELECT MIN(id) FROM images)) LIMIT 1");
// $vars = array(':id' => $id);
$prev = $stmt_a->execute(array( (int)$id ));
$next = $stmt_b->execute(array( (int)$id ));
if ($stmt_a->rowCount() > 0) {
while($row = $stmt_a->fetch(PDO::FETCH_ASSOC)) {
echo 'Previous';
}
} else {
echo 'no previous';
}
if ($stmt_b->rowCount() > 0) {
while($row = $stmt_b->fetch(PDO::FETCH_ASSOC)) {
echo 'Next';
}
} else {
echo 'no next';
entre your db conection befor sentax like this:
<?
//enter your MySQL database host name, often it is not necessary to edit this line
$db_host = "localhost";
//enter your MySQL database username
$db_username = "your user name";
//enter your MySQL database password
$db_password = "your passwor";
//enter your MySQL database name
$db_name = "your db name";
//URL to the the site
$ScriptPath = "http://www.your-site.com/";
$db = mysqli_connect($db_host, $db_username, $db_password) or die("Error " . mysqli_error($db));
mysqli_select_db($db, $db_name) or die("Error " . mysqli_error($db));
function getNavID($id) {
$result4= mysqli_query($db, "SELECT
( SELECT id FROM products_list
WHERE id > '$id' LIMIT 1 ) AS nextValue,
( SELECT id FROM products_list
WHERE id < '$id' ORDER BY id DESC LIMIT 1 ) AS prevValue
FROM products_list
LIMIT 1");
if ($resultID = mysqli_fetch_array($db, $result4)) {
return $resultID;
}
else {
return NULL;
}
}
$LinkID = getNavID($id);
if (!is_null($LinkID['prevValue']))
{
?>
Previous
<?php
}
else if (!is_null($LinkID['nextValue']))
{
?>
Next
<?php
}
else
{
echo "No Entries";
}
?>

make php function with two different mysql command

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.

Categories