Php pagination for basic cms - php

I have a problem with pagination and I have to admit I am a newbie for programming in php .
I hope,you can tell me how to do pagination for those codes.
index.php , homepage function.
function homepage() {
$results = array();
$data = Article::getList( HOMEPAGE_NUM_ARTICLES );
$results['articles'] = $data['results'];
$results['totalRows'] = $data['totalRows'];
$results['pageTitle'] = "Widget News";
require( TEMPLATE_PATH . "/homepage.php" );
}
Article.php get article function
public static function getList( $numRows=1000000, $order="publicationDate DESC" ) {
$conn = new PDO( DB_DSN, DB_USERNAME, DB_PASSWORD );
$sql = "SELECT SQL_CALC_FOUND_ROWS *, UNIX_TIMESTAMP(publicationDate) AS<br> publicationDate FROM articles
ORDER BY " .$order. " LIMIT :numRows";
$st = $conn->prepare( $sql );
$st->bindValue( ":numRows", $numRows, PDO::PARAM_INT );
$st->execute();
$list = array();
while ( $row = $st->fetch() ) {
$article = new Article( $row );
$list[] = $article;
}
index.php show article foreach
<?php foreach ($results['articles'] as $article){?>
<li>
<h2>
<span class="pubDate"><?php echo date('j F',$article->publicationDate)?></span>
<a href=".?action=viewArticle&articleId=<?php echo $article->id?>">
<?php echo htmlspecialchars($article->title)?>
</a>
</h2>
<p class="summary"><?php echo htmlspecialchars($article->summary)?></p>
</li>
<?php }?>
Thank you.

You need to use OFFSET in MySql string.
$page = isset($_GET['page']) ? $_GET['page'] : 1;
$itemsPerPage = 10;
$offset = ($page * $itemsPerPage) - $itemsPerPage;
$sql = "SELECT * FROM articles OFFSET {$offset} LIMIT {$itemsPerPage}";
Also remove <br> from your code. It's only valid for HTML, elsewhere it will throw error.
Final function (start) would look like this:
public static function getList($numRows = 10, $order = "publicationDate DESC") {
$conn = new PDO(DB_DSN, DB_USERNAME, DB_PASSWORD);
$page = isset($_GET['page']) ? $_GET['page'] : 1;
$order = preg_replace("/[^a-zA-Z\s]/", '', $order);
$numRows = intval($numROws);
$offset = ($page * $numRows) - $numRows;
$sql = "SELECT
SQL_CALC_FOUND_ROWS *,
UNIX_TIMESTAMP(`publicationDate`) AS 'publicationDate'
FROM `articles`
ORDER BY {$order}
LIMIT :numRows
OFFSET :offset";
$st = $conn->prepare( $sql );
$st->execute(array(':numRows' => $numRows, ':offset' => $pffset));

Related

select based on random value if not exist change value php

I'm trying to select values from database where date is equal to random date and sometimes there is no records how can I run the select again with another random value without refreshing website?
$start = "2017-08-12";
$now = date("Y-m-d");
$now = date('Y-m-d', strtotime($now. ' - 7 days'));
$daty = array();
while($start<$now){
$start = date('Y-m-d', strtotime($start. ' + 7 days'));
$daty[] = $start;
}
$rand_keys = array_rand($daty, 2);
$random_data = $daty[$rand_keys[0]] ;
$sql2= 'SELECT count(*) as total from tab where
Date="'.$random_data.'"';
$result12 = mysqli_query( $conn, $sql2 );
$row12 = $result12->fetch_assoc();
if($row12>0){
$sql1 = 'select * from premier1718 where Date="'.$random_data.'"';
$result1 = mysqli_query( $conn, $sql1 );
while($row1 = $result1->fetch_assoc()){
echo $row1["HomeTeam"]." ".$row1["AwayTeam"]."</br>";
}
I think you can possibly do this in one query like this
$sql = 'select * from `premier1718` where `date`=(
select `date` from `tab` where `date` in ( "'.implode( '","', $daty ).'" ) order by rand() limit 1
)';
$result = mysqli_query( $conn, $sql );
if( $result ){
while( $rs=$result->fetch_object() ) printf('%s %s<br />',$rs->hometeam,$rs->awayteam);
}
$rand_keys = array_rand($daty, 2);
$random_data = $daty[$rand_keys[0]] ;
$sql2= 'SELECT count(*) as total from tab where
Date="'.$random_data.'"';
$result12 = mysqli_query( $conn, $sql2 );
$row12 = $result12->fetch_assoc();
if($row12>0){
$success = false;
while ($success == false) {
$sql1 = 'select * from premier1718 where Date="'.$random_data.'"';
$result1 = mysqli_query( $conn, $sql1 );
while($row1 = $result1->fetch_assoc()){
$success = true;
echo $row1["HomeTeam"]." ".$row1["AwayTeam"]."</br>";
}
}

PHP MYSQL Pagination CMS

(this code was updated after some answer from another topic: How do I Paginate my CMS)
I've been following the Build a CMS in an Afternoon tutorial at http://www.elated.com/articles/cms-in-an-afternoon-php-mysql/ .
The CMS works great but the only thing it's lacking is pagination. The article archive displays the list of all of the articles that are in the database, but I want to be able to separate these into pages. I've attempted it a few times but can never seem to get it to work. Clicking on a next page link usually brings me back to the homepage.
I will apreciate your help
The code:
ARTICLE
public static function getList( $numRows=130, $order="publicationDate DESC" ) {
$conn = new PDO( DB_DSN, DB_USERNAME, DB_PASSWORD );
$offset = ($_GET['page'] - 1) * $numRows;
$rowCount = 20;
$sql = "SELECT SQL_CALC_FOUND_ROWS *, UNIX_TIMESTAMP(publicationDate) AS publicationDate FROM articles
ORDER BY " . mysql_escape_string($order) . " LIMIT :offset, :rowCount";
$st = $conn->prepare( $sql );
$st->bindValue( ":offset", $offset, PDO::PARAM_INT );
$st->bindValue( ":rowCount", $rowCount, PDO::PARAM_INT );;
$st->execute();
$list = array();
while ( $row = $st->fetch() ) {
$article = new Article( $row );
$list[] = $article;
}
// Now get the total number of articles that matched the criteria
$sql = "SELECT FOUND_ROWS() AS totalRows";
$totalRows = $conn->query( $sql )->fetch();
$conn = null;
return ( array ( "results" => $list, "totalRows" => $totalRows[0] ) );
}
$st = $conn->prepare( $sql ); $st->bindValue( ":offset", $offset, PDO::PARAM_INT ); $st->bindValue( ":rowCount", $rowCount, PDO::PARAM_INT );;
$st->execute();
$list = array();
while ( $row = $st->fetch() ) {
$article = new Article( $row );
$list[] = $article;
}
// Now get the total number of articles that matched the criteria
$sql = "SELECT FOUND_ROWS() AS totalRows";
$totalRows = $conn->query( $sql )->fetch();
$conn = null;
return ( array ( "results" => $list, "totalRows" => $totalRows[0] ) ); }
ARQUIVE
<ul class="noticias_archive">
<?php foreach ( $results['articles'] as $article ) { ?>
<li>
<div class="noticias_archive col-4">
<?php if ( $imagePath = $article->getImagePath( IMG_TYPE_THUMB ) ) { ?>
<img class="articleImageThumb" src="<?php echo $imagePath?>" alt="Article Thumbnail" />
<?php } ?></div>
<div class="noticias_archive col-4">
<h3 class="top">
<?php echo htmlspecialchars( $article->title )?>
</h3>
<p>
<?php echo htmlspecialchars( $article->summary )?><br><br><?php echo date('j F Y', $article->publicationDate)?></p>
</div>
</li>
<?php } ?>
</ul>
</div>
<p>
<?php
if ( isset( $_GET['page'] ) ){
echo sprintf('<p> << Back </p>', $_GET['page'] - 1);
echo sprintf('<p> Next >> </p>', $_GET['page'] + 1);}?> in total.</p>
<p>Return to Homepage</p>
INDEX
require( "config.php" );
$action = isset( $_GET['action'] ) ? $_GET['action'] : "";
switch ( $action ) {
case 'noticias':
noticias();
break;
case 'viewArticle':
viewArticle();
break;
default:
homepage();
}
function noticias() {
$results = array();
$data = Article::getList();
$results['articles'] = $data['results'];
$results['totalRows'] = $data['totalRows'];
$results['pageTitle'] = "Article Archive | teste";
require( TEMPLATE_PATH . "/archive.php" );
}
function viewArticle() {
if ( !isset($_GET["articleId"]) || !$_GET["articleId"] ) {
homepage();
return;
}
$results = array();
$results['article'] = Article::getById( (int)$_GET["articleId"] );
$results['pageTitle'] = $results['article']->title . " | teste2";
require( TEMPLATE_PATH . "/viewArticle.php" );
}
function homepage() {
$results = array();
$data = Article::getList( HOMEPAGE_NUM_ARTICLES );
$results['articles'] = $data['results'];
$results['totalRows'] = $data['totalRows'];
$results['pageTitle'] = "FPT - teste3";
require( TEMPLATE_PATH . "/homepage.php" );
}

NOTICE: Undefined index: Page

I dont understand what im doing wrong, im getting this message:
Notice: Undefined index: page in /Users/prinect/htdocs/sistema-noticias/classes/Article.php on line 221
My code:
public static function getList( $numRows=30, $order="publicationDate DESC" ) {
$conn = new PDO( DB_DSN, DB_USERNAME, DB_PASSWORD );
$offset = ($_GET['page'] - 1) * $numRows;
$rowCount = 20;
$sql = "SELECT SQL_CALC_FOUND_ROWS *, UNIX_TIMESTAMP(publicationDate) AS publicationDate FROM articles
ORDER BY {$order} LIMIT :offset, :rowCount";
$st = $conn->prepare( $sql );
$st->bindValue( ":rowCount", $rowCount, PDO::PARAM_INT );
$st->bindValue( ":offset", $offset, PDO::PARAM_INT );
$st->execute();
$list = array();
while ( $row = $st->fetch() ) {
$article = new Article( $row );
$list[] = $article;
}
// Now get the total number of articles that matched the criteria
$sql = "SELECT FOUND_ROWS() AS totalRows";
$totalRows = $conn->query( $sql )->fetch();
$conn = null;
return ( array ( "results" => $list, "totalRows" => $totalRows[0] ) );
}
Undefined index means in your case that you are trying to access to an element of an array that does not exist.
It is most likely your $_GET['page']. Do you check if this exists? You should.
For example:
$page = (isset($_GET['page']) ? $_GET['page'] : 1; // 1 is the default page number
you need to check the page if it don't exist because when the page is not in the query param it will be considered as undefined
$page = isset($_GET['page']) ? $_GET['page'] : 1;
$offset = ($page - 1) * $numRows;
$rowCount = 20;

Passing variable to static function

I have some PHP that pulls all staff records in the DB.
I now want to add a clause, so it can SELECT * WHERE companyId = x.
Im using GET to retrieve the companyId to be used.
My question is, how can I pass $companyClause to the static function?
function viewStaffInCompany(){
$results = array();
$companyClause = $_GET["companyClause"];
echo $companyClause . "<br><hr>";
$data = Staff::getCompanyStaffList();
$results['staff'] = $data['results'];
$results['totalRows'] = $data['totalRows'];
require( "templates/viewStaff.php" );
};
and
getCompanyStaffList();
public static function getCompanyStaffList( $numRows=1000000, $order="id ASC", $companyClause) {
$conn = new PDO( DB_DSN, DB_USERNAME, DB_PASSWORD );
$sql = "SELECT SQL_CALC_FOUND_ROWS * FROM Staff WHERE $companyClause ORDER BY " . $order . " LIMIT :numRows";
$st = $conn->prepare( $sql );
$st->bindValue( ":numRows", $numRows, PDO::PARAM_INT );
$st->execute();
$list = array();
while ( $row = $st->fetch() ) {
$users = new Staff( $row );
$list[] = $users;
}
// Now get the total number of staff that matched the criteria
$sql = "SELECT FOUND_ROWS() AS totalRows";
$totalRows = $conn->query( $sql )->fetch();
$conn = null;
return ( array ( "results" => $list, "totalRows" => $totalRows[0] ) );
}
Just as a parameter.
Staff::getCompanyStaffList(1000000, "id ASC", $companyClause);
But I would refactore this parameter list, because $companyClause is required, so, you will need to pass the first 2 params always, what has default values, if not given.
So it should be:
public static function getCompanyStaffList($companyClause, $numRows=1000000, $order="id ASC") {

Using recurssion in deleting parent and child relationship in mysql table

I'm having trouble getting this function work. This is my database design
I'm working in an application wherein when a user deletes a parent category, all the subcategory would also be deleted, and so on and so fort..
For example:
When the user clicks on the "Test1" category in my application, the "Test1.1" and "Test1.1.1" would be deleted since it is under the "Test1" category.
This is my database design(above).
This is the code that I wrote:
function DeleteProjectPhotos( $cat_id ) {
$sql = "SELECT * FROM project_category WHERE category_id = '$cat_id'";
$query = mysql_query( $sql ) or die( mysql_error() );
if( mysql_num_rows( $query ) > 0 ) {
$sql = "SELECT * FROM project_category WHERE parent_id = '$cat_id'";
$query = mysql_query( $sql ) or die( mysql_error() );
if( mysql_num_rows( $query ) > 0 ) {
while( $row = mysql_fetch_assoc( $query ) ) {
$this->DeleteProjectPhotos( $row['category_id'] );
}
} else {
$sql = "DELETE FROM project_category WHERE category_id = '$cat_id'";
$query = mysql_query( $sql ) or die( mysql_error() );
}
}
}
But I think the whole logic here is wrong because when I try to delete the category_id 33, everything won't be deleted. Kindly teach me how to do this one.
Your help would be greatly appreciated and rewarded!
Thanks! :)
<?php
$catID = $_GET['catID'];
deleteCategory($catID);
function connect(){
$host = 'localhost';
$dbName = 'sony';
$userName = 'root';
$password = '';
$conn = new PDO("mysql:host=$host;dbname=$dbName",$userName,$password);
$conn->setAttribute(PDO::ATTR_ERRMODE,PDO::ERRMODE_EXCEPTION);
return $conn;
}
$stmt = '';
function deleteCategory($catID){
$conn = connect();
$tableName = 'childparent';
$sql = "select catID from $tableName where parentID = :catID";
global $stmt;
$stmt = $conn->prepare($sql);
$idsToDelete = getChilds($catID);
$idsToDelete[] = $catID;
//print_r($idsToDelete);
$delExp = '';
foreach($idsToDelete as $id)
$delExp .= " catID=$id or";
$delExp = preg_replace('/or$/','',$delExp);
if($delExp != ''){
$delSql = "delete from $tableName where $delExp";
//echo $delSql;
$delStmt = $conn->prepare($delSql);
$delStmt->execute();
}
}
$collectedIDs = array();
function getChilds($catID){
global $stmt,$collectedIDs;
$stmt->bindValue(':catID',$catID);
$stmt->execute();
$childCatIDs = array();
while($row = $stmt->fetch(pdo::FETCH_ASSOC)){
$childCatIDs[] = $row['catID'];
$collectedIDs[] = $row['catID'];
}
//print_r($childCatIDs);
//die();
if(!empty($childCatIDs)){
foreach($childCatIDs as $cid)
getChilds($cid);
}
return $collectedIDs;
}
?>
If you don't want triggers you can try http://php.net/manual/en/function.mysql-affected-rows.php on delete category you get it`s id and while there is a return you try to delete by cathegory or by parent

Categories