Very strange occurence mysql php blog - php

Ok so the problem I'm having is very strange. I have a blog website that displays a list of posts, and i made a system to select only 10 posts at a time. and yet on the second generated page 12 results are shown (the last 2 are duplicates)
//removed url because problem solved and i dont want to get sql injected
if you goto my project above and look at the second page of posts 12 entry's are shown with the last 2 being duplicates of the 3rd(and last) page...what is going on?! they should not be able to appear because the sql LIMIT function should restrict the displayed posts to 10.
here is the code for mainpage .php
<?php
session_start();
ob_start();
if ($_SERVER["REQUEST_METHOD"] == "POST"){//this works in my tests.
$low = 0;
$high = 10; //this loop/if method works in conjunction with the code at the bottom of this page
$e = 1;//starts at 1 because 1 itself is defined my default at the bottom of the page
while($_SESSION['i'] != $e){
$e++;
if (isset($_REQUEST["p$e"])){
$u = 1;
while($u != $e){
$u++;
$low = $low + 10;
$high = $high +10;
}
}
}}else{
$low = 0;
$high = 10;
}
?>
<!doctype html>
<!-- AUTHOR:JOSH FAIRBANKS -->
<html lang="en">
<head>
<meta charset="utf-8">
<title>Home Page</title>
<link rel="stylesheet" href="style.css">
</head>
<body>
<nav>
<ul>
<li><div id = "new">Create new post</div></li>
<li><div id = "veiw">Veiw posts</div></li>
</ul>
</nav>
<main>
<?php
$link = mysqli_connect( 'localhost', 'username', 'password' );
mysqli_select_db( $link, 'mydatabasename' );
$results = mysqli_query( $link, "SELECT LEFT(post, 575) as post FROM Users where verified = 1 ORDER BY `id` DESC LIMIT $low , $high" ); //this displayes all the posts that have been verified
while( $record = mysqli_fetch_assoc( $results ) ) {
$post = $record['post'];
$count = mysqli_affected_rows( $link );
//ORDER BY YEAR(Date) DESC, MONTH(Date) DESC, DAY(DATE) DESC
$post .= "</td></tr></table>";
print $post;
}
$vresults = mysqli_query( $link, "SELECT post FROM Users where verified = 1" );
while( $vrecord = mysqli_fetch_assoc( $vresults ) ) {
$vpost = $vrecord['post'];
$vcount = mysqli_affected_rows( $link );
$_SESSION['vcount'] = $vcount;
//
//these mirror variables arent seen and just are used to count the total amount of posts
//not just the ones on the page
}
mysqli_free_result( $results );
mysqli_close( $link );
?>
<form method = "post" action = "mainPage.php">
<table>
<tr><td>Page Number: </td><!--<td><input type = "submit" name = "p1" value = "1"></td>-->
<?php
$i = 0;
print "displaying low: $low high: $high";
for($j = 0; $j < $vcount; $j++) //modulus
{
if($j % 10 == 0)
{
$i++;
$_SESSION['i'] = $i;
print "<td><input type = 'submit' name ='"."p".$i. "' value = '$i'></td>";
}
}
?>
</tr>
</table>
</form>
</main>
</body>
</html>
I know this code is a bit of a mess :p but i swear it works except for this frustrating issue. any and all help appreciated.

I guess your problem at $high variable... Records per page always constant. But seems that you are increment in one place.
if ($_SERVER["REQUEST_METHOD"] == "POST"){//this works in my tests.
$low = 0;
$high = 10; //this loop/if method works in conjunction with the code at the bottom of this page
$e = 1;//starts at 1 because 1 itself is defined my default at the bottom of the page
while($_SESSION['i'] != $e){
$e++;
if (isset($_REQUEST["p$e"])){
$u = 1;
while($u != $e){
$u++;
$low = $low + 10;
$high = 10;
}
}
}}else{
$low = 0;
$high = 10;
}
?>

Related

PHP: Dividing mysql result to four div

I have category table which include 35 category inside. I want them aline into four div with one while loop.
<?php
$count = 0;
$cat = pullcategories();
$catcount = mysqli_num_rows($cat);
$percat = ceil($catcount / 4);
$topcats = pulltopcategories($count, $percat);
//same with pullcategories, just LIMIT $count,$per //
while ($topcats = mysqli_fetch_object($topcats)) {
?>
<div class="col3">
<ul class="list-unstyled list-dashed">
<li>
$topcats->title
</li>
</ul>
</div>
<?php
$count = $count + $percat;
$percat = $percat * 2;
}
?>
$count = 0;
$cat = pullcategories();
$catcount = mysqli_num_rows($cat);
$percat = ceil($catcount / 4);
$topcats = pulltopcategories($count, $percat);
This breaks your lists down in to 4 parts, and you would need to call "$topcats = pulltopcategories($count, $percat);" 4 times to be able to get through all the data.
I would change it to be something like this.
Assuming that "pulltopcategories($count, $percat)" uses count as the limit, and percat as the offset in the SQL this should work.
Please try and let me know - I can fix any mistakes if there are any (my PHP is a little rusty and i dont have data to try this with)
<?php
$count = 0;
$cat = pullcategories();
$catcount = mysqli_num_rows($cat);
$percat = ceil($catcount / 4);
while ($count < catcount){ /* Loop until you have finished all cats */
$topcats = pulltopcategories($count, $percat);
echo "<div class="col3">
<ul class='list-unstyled list-dashed'>";
while ($topcats = mysqli_fetch_object($topcats)) {
echo "<li>
<a href=''>$topcats->title</a>
</li>"
}
echo "</ul>
</div>";
$count = $count + $percat;
}
?>

I don't get all the data from mysql - PHP

I've been searching for this for while but didn't find anything related.
So my problem is that I do get all the data from mysql with while(). However, all the articles I am trying to get displays as only 1 article even though the content is different. Sorry, it's not easy to explain that but see pictures below:
My database:
How it is displayed:
my articlesFunction.php code:
// check if user is logged in to view the content:
if(!isset($_SESSION['loggedin']) && !isset($_SESSION['loggedinAdmin'])){
header("Location: login.php");
}else{
}
//
$sql = "SELECT * FROM `articles` ORDER BY id DESC";
$result = mysql_query($sql);
while($row = mysql_fetch_assoc($result)){
$displayUsername = $row['username'];
$displayArticleName = $row['name'];
$displayArticleDescription = $row['description'];
$fullArticle = 'Article name: '.$displayArticleName.'<br/> This article was posted by: '.$displayUsername.'<br/>'.$displayArticleDescription.'<hr/>';
}?>
//
my articles.php:
<?php
///////////////////////////////////////////////////////////////////////////////////////
// UNFINISHED //
///////////////////////////////////////////////////////////////////////////////////////
session_start();
require_once 'connect.php';
include 'articlesFunction.php';
?>
<html>
<head>
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Blog posts</title>
<link rel="stylesheet" href="css/articles.css">
</head>
<body>
<div id="bannerDiv" style="background-image: url(images/banner.jpg); background-size: 100% 100%; height:150px;">
<h2 id="bannerTitle"><u><i>Articles about travel that everyone loves...</i></u></h2>
<p>Homepage</p>
<span id="BannerMenu"><?php echo 'logged in as: '.$_SESSION['username'].' ';?></span><button>Logout</button>
</div>
<div id="container">
<div id="articles">
<div id="Display Articles">
<h1><u>Our set of articles:</u>
</h1>
<div id="display">
<?php
echo $fullArticle;
?>
</div>
</div>
</div>
</div>
</body>
</html>
So, I hope you understand my issue now. First, in this example, when I put it alone in the div, I only get the oldest article and I get only 1. If I add a while to the div, It gives me the results in the picture above:
So, how can I display the articles (all of them) and each one to be different as they are in the database.
You are overwriting your variable on every iteration of the while loop.
while($row = mysql_fetch_assoc($result)){
$displayUsername = $row['username'];
$displayArticleName = $row['name'];
$displayArticleDescription = $row['description'];
$fullArticle = 'Article name: '.$displayArticleName.'<br/> This article was posted by: '.$displayUsername.'<br/>'.$displayArticleDescription.'<hr/>';
}
so as a simple example
$a = 0;
$b = 3;
while($a < $b){
$output = $a;
$a++;
}
echo $output;
This gives back 2 because $output is being over written every-time. There are two approaches to keeping all the values.
Option one, concatenate the variable
$a = 0;
$b = 3;
$output = '';
while($a < $b){
$output .= $a;
$a++;
}
echo $output;
Which will output 012. We have to define the variable before using it with the .=. With the .= it is trying to concatenate the value first so it must already exist.
Option two, store the values in an array
$a = 0;
$b = 3;
while($a < $b){
$output[] = $a;
$a++;
}
print_r($output);
This will output:
Array
(
[0] => 0
[1] => 1
[2] => 2
)
This way is a bit more work because when you want to access it later you have to re-iterate through it. However it can be better if you want to be able to access each data point separately.
foreach($output as $value) {
echo $value;
}
Also note if users are providing their usernames, article name, or description and you aren't filtering that this will open you to XSS injections.
https://en.wikipedia.org/wiki/Cross-site_scripting
https://www.owasp.org/index.php/XSS_(Cross_Site_Scripting)_Prevention_Cheat_Sheet#A_Positive_XSS_Prevention_Model
Usage in your actual code would be:
$sql = "SELECT * FROM `articles` ORDER BY id DESC";
$result = mysql_query($sql);
$fullArticle = '';
while($row = mysql_fetch_assoc($result)){
$displayUsername = $row['username'];
$displayArticleName = $row['name'];
$displayArticleDescription = $row['description'];
$fullArticle .= 'Article name: '.$displayArticleName.'<br/> This article was posted by: '.$displayUsername.'<br/>'.$displayArticleDescription.'<hr/>';
}?>
This should be your code, in order to avoid the errors you mentioned in the comments;
//init fullname variable
$fullArticle = '';
while($row = mysql_fetch_assoc($result)){
$displayUsername = $row['username'];
$displayArticleName = $row['name'];
$displayArticleDescription = $row['description'];
$fullArticle .= 'Article name: '.$displayArticleName.'<br/> This article was posted by: '.$displayUsername.'<br/>'.$displayArticleDescription.'<hr/>';
}?>
//

Ajax Paging with php and mysql

I am trying to setup paging on my site using Ajax, I've inherited a script and put it into practice at the following link - http://www.testing.arrivaldesign.co.uk/properties.
I've got it working to an extent, but it's set to show the first 9 records and then carry on from there, but it's only showing the first 9 on the first page, but then when you click to the next page it just repeats 4 of the existing records.
As far as I can see it's to do with limit on my query, but I don't know how to get it working?
This is the code for the ajax side of things.
<?php
include('Connections/connection.php');
include 'functions.php';
// Pagination params
$basePath = 'http://' . $_SERVER['SERVER_NAME'] . $_SERVER['PHP_SELF'];
$qString = $_REQUEST['qString'];
$items = $_REQUEST['items'];
$loadPage = $_REQUEST['p'];
$current = $_REQUEST['current'];
$limit = $loadPage*$items;
$min = ($max-$items)+1;
mysql_select_db($database, $conn);
$query_RSproperty = "SELECT properties.*, type.* FROM (properties LEFT JOIN type ON properties.propType=type.typeID) WHERE offline = 'N' ORDER BY propID ASC LIMIT 0, $limit";
$RSproperty = mysql_query($query_RSproperty, $conn) or die(mysql_error());
$row_RSproperty = mysql_fetch_assoc($RSproperty);
$totalRows_RSproperty = mysql_num_rows($RSproperty);
$maxItems = $totalRows_RSproperty;
// New pagination
$pagination = paginator($basePath . $qString, $loadPage, $maxItems, $items);
// Direction is important for the script to determine which way to animate, left or right.
$direction = 'left';
if ($current < $loadPage) {
$direction = 'right';
}
$paginatedStyle = 'style="left:'.($direction == 'left' ? '0' : '-960px').';"';
// The paginated content HTML slide
$page = '<div class="paginated" id="" '.$paginatedStyle.'>';
ob_start();
do {
?>
<div class="grid-1third res-block">
<div class="prop-brief-desc">
<div class="grid-140"><img src="/prop-images/thumbs/<?php echo $row_RSproperty['propImage1']; ?>" width="140" height="105" alt=""></div>
<div class="grid-140 fr">
<h2><?php echo $row_RSproperty['propBeds']; ?> Bed <?php echo $row_RSproperty['typeName']; ?></h2>
<?php
$fulladdress = $row_RSproperty['propAddress1'] . '<br />' . $row_RSproperty['propCity'] . ', ' . $row_RSproperty['propCounty'] . '<br />' . $row_RSproperty['propPostcode'];
?>
<p><?php echo $fulladdress; ?></p>
</div>
</div>
<div class="prop-brief-options<?php echo $no == 2 || $no == 3 ? " hide" : ""; ?>" id="newopt<?php echo $no; ?>">
<div class="grid-140"> Details Arrange Viewing Place Bid Buy it Now </div>
<div class="grid-140 fr">
<dl>
<dt>Auction Ending:</dt>
<dd><?php
if(!function_exists('countdown')) {
function countdown($year, $month, $day, $hour, $minute) {
$the_countdown_date = mktime($hour, $minute, 0, $month, $day, $year, -1);
$current = time();
$difference = $the_countdown_date - $current;
if ($difference < 0) $difference = 0;
$days = floor($difference/60/60/24);
$hours = floor(($difference - $days*60*60*24)/60/60);
$minutes = floor(($difference - $days*60*60*24 - $hours*60*60)/60);
echo $days."d ".$hours."h ".$minutes."m";
}
}
$theyear = date("Y",strtotime($row_RSproperty['propEndDate']));
$themonth = date("n",strtotime($row_RSproperty['propEndDate']));
$theday = date("d",strtotime($row_RSproperty['propEndDate']));
$thehour = date("H",strtotime($row_RSproperty['propEndDate']));
$theminute = date("i",strtotime($row_RSproperty['propEndDate']));
countdown($theyear,$themonth,$theday,$thehour,$theminute);
?></dd>
<?php if ($row_RSproperty['propCurrBid'] > 0) { ?>
<dt>Current bid:</dt>
<dd>£<?php echo number_format($row_RSproperty['propCurrBid']); ?></dd>
<?php } else { ?>
<dt>Starting Price:</dt>
<dd>£<?php echo number_format($row_RSproperty['propStartPrice']); ?></dd>
<?php } ?>
<dt>Buy it now:</dt>
<dd><span class="green">£<?php echo number_format($row_RSproperty['propBinPrice']); ?></span></dd>
</dl>
</div>
</div>
</div>
<?php
} while ($row_RSproperty = mysql_fetch_array($RSproperty));
/*while ($min <= $max) {
$page .= '<li>'.$min.'</li>';
$min++;
}*/
$page .= ob_get_contents();
ob_end_clean();
$page .= '</div>';
// return the JSON
echo json_encode(array( 'pagination' => $pagination, 'page' => $page, 'current' => $loadPage ));
exit;
?>
Many thanks
Chris
That's because you have hard coded LIMIT as 0 in your query
$query_RSproperty = "SELECT properties.*, type.* FROM (properties LEFT JOIN type ON properties.propType=type.typeID) WHERE offline = 'N' ORDER BY propID ASC LIMIT 0, $limit";
So when you move on second page, the query must be getting generated like follow
$query_RSproperty = "SELECT properties.*, type.* FROM (properties LEFT JOIN type ON properties.propType=type.typeID) WHERE offline = 'N' ORDER BY propID ASC LIMIT 0, 4";
hence you re getting first 4 records. If you want to retrieve the next set of records on subsequent pages, then you have to make 0 in LIMIT 0, $limit dynamic like:
$query_RSproperty = "SELECT properties.*, type.* FROM (properties LEFT JOIN type ON properties.propType=type.typeID) WHERE offline = 'N' ORDER BY propID ASC LIMIT $offset, $limit";
You have to calculate $offset depending on how much results you are displaying per page. On first page, offset will always be 0. If you are displaying 10 records per page, then on second page, offset will be 11, on third offset will be 21 and so on.

Using for loop to speed up PHP code typing

Hi everyone I've been extracting rows from a SQL table 1 by 1. I wrote this code two years ago and realise how hideously ineffective it is. I'd like to speed things up by typing up a simple for-loop to automate the coding.
$maxRows_dd1 = 10;
$pageNum_dd1 = 0;
if (isset($_GET['pageNum_dd1'])) {
$pageNum_dd1 = $_GET['pageNum_dd1'];
}
$startRow_dd1 = $pageNum_dd1 * $maxRows_dd1;
$maxRows_dd2 = 10;
$pageNum_dd2 = 1;
if (isset($_GET['pageNum_dd2'])) {
$pageNum_dd2 = $_GET['pageNum_dd2'];
}
$startRow_dd2 = $pageNum_dd2 * $maxRows_dd2;
$maxRows_dd3 = 10;
$pageNum_dd3 = 2;
if (isset($_GET['pageNum_dd3'])) {
$pageNum_dd3 = $_GET['pageNum_dd3'];
}
$startRow_dd3 = $pageNum_dd3 * $maxRows_dd3;
... dd4 to dd99 go in between!
$maxRows_dd100 = 10;
$pageNum_dd100 = 99;
if (isset($_GET['pageNum_dd99'])) {
$pageNum_dd32 = $_GET['pageNum_dd99'];
}
$startRow_dd99 = $pageNum_dd99 * $maxRows_dd99;
which corresponds to:
mysql_select_db($database_rent, $rent);
$query_dd1 = "SELECT * FROM rent";
$query_limit_dd1 = sprintf("%s LIMIT %d, %d", $query_dd1, $startRow_dd1, $maxRows_dd1);
$dd1 = mysql_query($query_limit_dd1, $rent) or die(mysql_error());
$row_dd1 = mysql_fetch_assoc($dd1);
if (isset($_GET['totalRows_dd1'])) {
$totalRows_dd1 = $_GET['totalRows_dd1'];
} else {
$all_dd1 = mysql_query($query_dd1);
$totalRows_dd1 = mysql_num_rows($all_dd1);
}
$totalPages_dd1 = ceil($totalRows_dd1/$maxRows_dd1)-1;
mysql_select_db($database_rent, $rent);
$query_dd2 = "SELECT * FROM rent";
$query_limit_dd2 = sprintf("%s LIMIT %d, %d", $query_dd2, $startRow_dd2, $maxRows_dd2);
$dd2 = mysql_query($query_limit_dd2, $rent) or die(mysql_error());
$row_dd2 = mysql_fetch_assoc($dd2);
if (isset($_GET['totalRows_dd2'])) {
$totalRows_dd2 = $_GET['totalRows_dd2'];
} else {
$all_dd2 = mysql_query($query_dd2);
$totalRows_dd2 = mysql_num_rows($all_dd2);
}
$totalPages_dd2 = ceil($totalRows_dd2/$maxRows_dd2)-1;
mysql_select_db($database_rent, $rent);
$query_dd3 = "SELECT * FROM rent";
$query_limit_dd3 = sprintf("%s LIMIT %d, %d", $query_dd3, $startRow_dd3, $maxRows_dd3);
$dd3 = mysql_query($query_limit_dd3, $rent) or die(mysql_error());
$row_dd3 = mysql_fetch_assoc($dd3);
if (isset($_GET['totalRows_dd3'])) {
$totalRows_dd3 = $_GET['totalRows_dd3'];
} else {
$all_dd3 = mysql_query($query_dd3);
$totalRows_dd3 = mysql_num_rows($all_dd3);
}
$totalPages_dd3 = ceil($totalRows_dd3/$maxRows_dd3)-1;
... all the way to dd100!!!
How would I use a for loop to speed typing up all this code for each block of code from dd1 to dd100?
Read about arrays and for() loops.
This is a much more efficient code to do exactly what you do above:
<?php
// You only need to do these once as they are the same throughout
mysql_select_db($database_rent, $rent);
$maxRows = 10;
// This code gets the total number of rows in the database
$totalRowsAll = mysql_fetch_assoc(mysql_query("SELECT count(*) AS total FROM rent", $rent));
$totalRowsAll = (int) $totalRowsAll['total'];
?>
<div class="tab_container">
<div id="tab1" class="tab_content">
<table width="100%" border="0" cellspacing="5" cellpadding="5" id="1">
<?php
for ($i = 0; $i < 100; $i++) {
// Calcluate value for this iteration and query database
$pageNum = (isset($_GET['pageNum_dd'.($i + 1)])) ? (int) $_GET['pageNum_dd'.($i + 1)] : $i;
$startRow = $pageNum * $maxRows;
$query = "SELECT * FROM rent LIMIT $startRow, $maxRows";
$result = mysql_query($query, $rent) or die(mysql_error($rent));
$totalRows = (isset($_GET['totalRows_dd1'])) ? (int) $_GET['totalRows_dd1'] : $totalRowsAll;
${'totalPages_dd'.($i + 1)} = ceil($totalRows / $maxRows) - 1;
// Now print this row
?>
<tr height="100px" align="center">
<?php
while ($row = mysql_fetch_assoc($query)) {
?>
<td style="background-color: <?php echo $row['colour']; ?>;" onclick="window.location='pay.php?id=<?php echo $row['dNo']; ?>&user=<?php echo $username; ?>'" onmouseover="this.style.cursor='pointer'">
<form action="pay.php?id=<?php echo $row['dNo']; ?>&user=<?php echo $username; ?>" method="post">
<input type="hidden" id="<?php echo $row['dNo']; ?>">
<input type="hidden" value="<?php echo $username; ?>">
<button type="submit" class="link" id="t<?php echo $row['dNo']; ?>">
<span><?php echo $row['dNo']; ?></span>
</button>
</form>
</td>
<?php
} // End while
?>
</tr>
<?php
} // End for
?>
</table>
</div>
</div>
...however:
I'm fairly sure this could be summed up in a single query to get all the results you need, which would be much more efficient and drastically reduce database load. But because of the $_GET['pageNum_dd*'] and $_GET['totalPages_dd*'] variables which are used on a per row basis, I am not 100% sure about this, and I can't work out how this would be done without knowing more about what is produced. You need to examine whether or not these parameters that can be passed are actually necessary/useful. As it is, they may be cause rows of a varying length, with an unequal number of cells per row - which is probably not what you want.
The same also goes for the variables $totalPages_dd*, which are assigned below but never used anywhere. They may not be useful, and assigning them may be pointless.

How to paginate a table of Mysql in PHP

I have a table in mysql.
Because it has many rows I want to put each 10 rows in a page and by clicking a link show me next 10 rows.
Is there any solution?
It was really really awesome http://www.phpsimplicity.com/tips.php?id=1
it is so simple! no need to work with huge classes! I'm Happy:D
<!DOCTYPE html>
<html lang="en">
<head>
<title>Paginate</title>
</head>
<body>
<form method='get'>
<?php
$connection = Mysql_connect( 'server', 'user', 'pass' );
if ( ! $connection ) {
echo 'connection is invalid';
} else {
Mysql_select_db( 'DB', $connection );
}
//Check if the starting row variable was passed in the URL or not
if ( ! isset( $_GET['startrow'] ) or ! is_numeric( $_GET['startrow'] ) ) {
//We give the value of the starting row to 0 because nothing was found in URL
$startrow = 0;
//Otherwise we take the value from the URL
} else {
$startrow = (int) $_GET['startrow'];
}
//This part goes after the checking of the $_GET var
$fetch = mysql_query( "SELECT * FROM sample LIMIT $startrow, 10" ) or
die( mysql_error() );
$num = Mysql_num_rows( $fetch );
if ( $num > 0 ) {
echo '
<table border=2>';
echo '
<tr>
<td>ID</td>
<td>Drug</td>
<td>quantity</td>
</tr>
';
for ( $i = 0; $i < $num; $i ++ ) {
$row = mysql_fetch_row( $fetch );
echo '
<tr>';
echo "
<td>$row[0]</td>
";
echo "
<td>$row[1]</td>
";
echo "
<td>$row[2]</td>
";
echo '
</tr>
';
}//for
echo '
</table>
';
}
//Now this is the link..
echo 'Next';
$prev = $startrow - 10;
//only print a "Previous" link if a "Next" was clicked
if ( $prev >= 0 ) {
echo 'Previous';
}
?>
</form>
</body>
</html>
By the way link of rickyduck was good too
I suggest checking out this link : http://php.about.com/od/phpwithmysql/ss/php_pagination.htm for basic pagination. Furthermore, if you have knowledge of javascript, you could use jQuery.

Categories