PHP MYSQL Pagination CMS - php

(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" );
}

Related

Displaying Database values in HTML

I am trying to get the values from table and display the values in the html code.
I am working in 3 separate php files.
This is the Article.php file, which contains the Article class:
public static function getInfobar() {
$conn = new PDO( DB_DSN, DB_USERNAME, DB_PASSWORD ); //connecting to the db, the values are stored in config.php
$sql = "SELECT 'title', 'subtitle', 'additional' FROM infobar WHERE id=1";
$st = $conn->prepare ( $sql );
$st->execute();
$list = array();
while ( $row = $st->fetch() ) { //storing the info inside the array.
$infob = new Article( $row );
$list[] = $infob;
}
$conn = null;
return ( array ( "results2" => $list));
}
After I pull these values from database, I'm trying to display them in the HTML. Firstly I declare a function inside the front-end handler: index.php
EDIT: the method is being called by using the switch.
switch ( $action )
{
default:
homepage();
}
function homepage() {
$results = array();
$results2 = array();
$data = Article::getList( HOMEPAGE_NUM_ARTICLES );
$data2 = Article::getInfobar();
$results['articles'] = $data['results'];
$results['totalRows'] = $data['totalRows'];
$results['pageTitle'] = "TITLE";
$results2['info'] = $data2['results2'];
require( TEMPLATE_PATH . "/homepage.php" );
}
After, I am trying to display the values in the webpage like this:
<div class="row_item1">
<?php foreach ( $results2['info'] as $infob ) { ?>
<h1><?php echo htmlspecialchars($infob->title)?></h1>
<p><?php echo htmlspecialchars($infob->subtitle)?></p>
<p><?php echo htmlspecialchars($infob->additional)?></p>
<?php } ?>
<img src="" alt="">
</div>
But all I get is this:
I am kinda stuck here, trying to figure out what's wrong with the code for quite awhile now. Please help me out on this one. Much appreciated.
Change your query
$sql = "SELECT 'title', 'subtitle', 'additional' FROM infobar WHERE id=1";
to
$sql = "SELECT title, subtitle, additional FROM infobar WHERE id=1";
For User Requirement.
I'm not sure. But, it can be like this way. Since, i don't know the flow, i can suggest you to try like this way once.
public static function getFullInfobar() {
.
.
$sql = "SELECT title, subtitle, additional FROM infobar";
.
.
}
$results3 = array();
$data3 = Article::getFullInfobar();
$results3['info'] = $data3['results3'];
<?php foreach ( $results3['info'] as $infob ) { ?>
<div class="row_item1">
<h1><?php echo htmlspecialchars($infob->title)?></h1>
<p><?php echo htmlspecialchars($infob->subtitle)?></p>
<p><?php echo htmlspecialchars($infob->additional)?></p>
<img src="" alt="">
</div>
<?php } ?>

Php pagination for basic cms

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));

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") {

replace $_GET with array of $userslist

im using this script through $_GET to add user name to my db beside it to my twitter list the script function well
for examlpe when i call it at url domain.com/add.php?user=username
the function of adding executed 100% fine
My doubt is about adjust the code to add multi users at once through array or get list of user from file
any tips to adjust the code or modify it ?
<?php
session_start();
require_once('dbconnect.php');
require_once('twitteroauth/twitteroauth.php');
require_once('config.php');
$connection = new TwitterOAuth(CONSUMER_KEY, CONSUMER_SECRET,TOKEN_KEY, TOKEN_SECRET);
$user = $_GET['user'];
if( !isset( $_GET['user'] ) )
die('You must enter a username');
$info = $connection->get( 'users/show', array("screen_name"=> $user
));
$var = $_GET['user'];
$individual = 1;
$protected = ($info->protected == "true")?1:0;
$query = sprintf("INSERT INTO tweeps VALUES('%s', '%s', %s, %s, '%s', '%s', '%s', %s ) ",
mysql_real_escape_string($info->screen_name),
mysql_real_escape_string($info->name),
$info->followers_count,
$info->statuses_count,
mysql_real_escape_string($info->location),
$info->created_at,
$info->profile_image_url,
$protected) ;
echo $query;
$result = mysql_query($query);
if(false)
echo "s";
else {
$list_id = get_latest_list();
$list = "Tweeps-" . $list_id;
echo "list $list";
mysql_free_result($result);
$connection = new TwitterOAuth(CONSUMER_KEY, CONSUMER_SECRET, TOKEN_KEY, TOKEN_SECRET);
$result = $connection->post( 'friendships/create/' . $info->screen_name );
//var_dump($result); die();
$result = $connection->post( 'lists/members/create', array("screen_name"=> $info->screen_name,
"slug"=> $list,
"owner_screen_name"=> "Tweeps") );
if( !isset($result->error) ) {
$userid = $info->id;
$result = mysql_query("INSERT INTO followed_tweeps(screenname, userid, individual, list_id) VALUES('" . $info->screen_name . "', '" . $userid . "', $individual, $list_id)");
}
}
echo "SUCCESS";
function get_latest_list() {
$query = "SELECT count(*) cnt, list_id FROM followed_tweeps group by list_id order by list_id desc";
$result = mysql_query($query);
if(! $result ) {
die("Error: query is $query error is: " . mysql_error() );
}
$row = mysql_fetch_row($result);
$cnt = $row[0];
$free_slots = 500 - $cnt;
$list_id = ($freeslots > 0) ? $row[1]++ : $row[1];
return $list_id;
}
?>
PHP supports an array notation for multiple same-name query parameters:
<input type="text" name="name[]" />
^^--- tells PHP to treat 'name' as an array
You can then process this as:
if (isset($_GET['name']) && isarray($_GET['name'])) {
foreach ($_GET['name'] as $name) {
...
}
}
This works regardless for both POST and GET - you just have to include the [] on the field name.

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