SELECT COUNT and Undefined offset issue - php

I'm having trouble trying to print a first name and surname for this SELECT COUNT (*) page below. If I delete the code which says "' . $row[6] . ' ' . $row[7] . '" the page works fine and prints the selected user's tally points rows only but not their first name and surname. I get the message below if I dont delete this code:
*
An error occurred in script 'database.php' on line 177: Undefined offset: 6 Date/Time: 3-8-2012 12:27:03
*
<?php # index.php
// Include the configuration file for error management and such.
require_once ('./includes/config.inc.php');
// Set the page title and include the HTML header.
$page_title = 'Individual Member Transactions';
include ('includes/header_admin_user.html');
// If no dealer_code variable exists, redirect the user.
if (!isset($_SESSION['admin_int_id'])) {
// Start defining the URL.
$url = 'http://' . $_SERVER['HTTP_HOST']
. dirname($_SERVER['PHP_SELF']);
// Check for a trailing slash.
if ((substr($url, -1) == '/') OR (substr($url, -1) == '\\') ) {
$url = substr ($url, 0, -1); // Chop off the slash.
}
// Add the page.
$url .= '/login.php';
ob_end_clean(); // Delete the buffer.
header("Location: $url");
exit(); // Quit the script.
}
// Check for a valid user ID, through GET or POST.
if ( (isset($_GET['id'])) && (is_numeric($_GET['id'])) )
{ // Accessed through view_users.php
$id = $_GET['id'];
} elseif ( (isset($_POST['id'])) && (is_numeric($_POST['id'])) )
{ // Form has been submitted.
$id = $_POST['id'];
} else { // No valid ID, kill the script.
echo '<h1 id="mainhead">Page Error</h1>
<p class="error">This page has been accessed in error.</p><p><br /><br /></p>';
include ('./includes/header_admin_user.html');
exit();
}
?>
<h1 id="mainhead">Points Transactions</h1>
<div id="sidebar">
<div id="statusbar">
<p><span class="statusbar_highlight">Name:</span><br />
<?php echo " {$_SESSION['adminfirstname']} " . " {$_SESSION['adminsurname']}<br> ";?></p>
<p><span class="statusbar_highlight">Status:</span><br />
<?php echo " {$_SESSION['adminstatus']} ";?></p>
<p><span class="statusbar_highlight">Employer:</span><br />
<?php echo " {$_SESSION['adminemployer']} ";?></p>
</div>
</div>
<div id="maincontent_results">
<?php
require_once ('database.php'); // Connect to the db.
// Number of records to show per page:
$display = 1000;
// Determine how many pages there are.
if (isset($_GET['np'])) { // Already been determined.
$num_pages = $_GET['np'];
} else { // Need to determine.
// Count the number of records
$query = "SELECT COUNT(*) FROM tally_point, users WHERE tally_point.users_id = users.users_id ORDER BY tally_points_entry_date DESC";
$result = #mysql_query ($query);
$row = #mysql_fetch_array ($result, MYSQL_NUM);
$num_records = $row[0];
// Calculate the number of pages.
if ($num_records > $display) { // More than 1 page.
$num_pages = ceil($num_records/$display);
} else {
$num_pages = 1;
}
} // End of np IF.
// Determine where in the database to start returning results.
if (isset($_GET['s'])) {
$start = $_GET['s'];
} else {
$start = 0;
}
// Default column links.
$link1 = "{$_SERVER['PHP_SELF']}?sort=lna";
$link2 = "{$_SERVER['PHP_SELF']}?sort=fna";
$link3 = "{$_SERVER['PHP_SELF']}?sort=dra";
// Determine the sorting order.
if (isset($_GET['sort'])) {
// Use existing sorting order.
switch ($_GET['sort']) {
case 'lna':
$order_by = 'tally_points_in ASC';
$link1 = "{$_SERVER['PHP_SELF']}?sort=lnd";
break;
case 'lnd':
$order_by = 'tally_points_in DESC';
$link1 = "{$_SERVER['PHP_SELF']}?sort=lna";
break;
case 'fna':
$order_by = 'total ASC';
$link2 = "{$_SERVER['PHP_SELF']}?sort=fnd";
break;
case 'fnd':
$order_by = 'total DESC';
$link2 = "{$_SERVER['PHP_SELF']}?sort=fna";
break;
case 'dra':
$order_by = 'tally_points_entry_date ASC';
$link3 = "{$_SERVER['PHP_SELF']}?sort=drd";
break;
case 'drd':
$order_by = 'tally_points_entry_date DESC';
$link3 = "{$_SERVER['PHP_SELF']}?sort=dra";
break;
default:
$order_by = 'tally_points_entry_date DESC';
break;
}
// $sort will be appended to the pagination links.
$sort = $_GET['sort'];
} else { // Use the default sorting order.
$order_by = 'tally_points_entry_date DESC';
$sort = 'dra';
}
// Select tally rows for the selected user and the users details
$query = "SELECT ta.tally_points_in, ta.order_id, ta.total, DATE_FORMAT(ta.tally_points_entry_date, '%d-%m-%Y') AS dr, ta.users_id, us.users_id, us.users_first_name, us.users_surname
FROM tally_point AS ta, users AS us
WHERE ta.users_id=$id
AND us.users_id = ta.users_id
ORDER BY
".$order_by." LIMIT ".$start.", ".$display;
$result = #mysql_query ($query);
// Table header.
echo ' ' . $row[6] . ' ' . $row[7] . '
<table width="400" cellspacing="1" cellpadding="7">
<tr class="top">
<td align="left"><b>Date</b></td>
<td align="center"><b>Credit</b></td>
<td align="center"><b>Debit</b></td>
<td align="center"><b>Description</b></td>
</tr>
';
// Fetch and print all the transactions.
$bg = '#ffffff'; // Set the background color.
while ($row = mysql_fetch_array($result, MYSQL_ASSOC)) {
$pointsitem = $row['order_id'];
$bg = ($bg=='#eaeced' ? '#ffffff' : '#eaeced'); // Switch the background color.
//$entries = floor($row['ltd_entry_amount']/200);
echo '<tr bgcolor="' . $bg . '">';
echo '<td align="left">' . $row['dr'] . '</td>';
echo '<td align="center"><strong>' . $row['tally_points_in'] . '</strong></td> ';
echo '<td align="center">' . $row['total'] . '</td>';
// products the footer, close the table, and the form.
$str = '<td align="center">';
if($pointsitem > '0') {
$str .='<strong>Order Details</strong></td></tr>';
}
else {
$str .='Monthly Points Update</td></tr>';
}
echo $str;
}
echo '</table>';
mysql_free_result ($result); // Free up the resources.
mysql_close(); // Close the database connection.
// Make the links to other pages, if necessary.
if ($num_pages > 1) {
echo '<br /><p>';
// Determine what page the script is on.
$current_page = ($start/$display) + 1;
// If it's not the first page, make a Previous button.
if ($current_page != 1) {
echo '<a href="view_points_2.php?s=' . ($start - $display) . '&np=' .
$num_pages . '&sort=' . $sort .'">Previous</a> ';
}
// Make all the numbered pages.
for ($i = 1; $i <= $num_pages; $i++) {
if ($i != $current_page) {
echo '<a href="view_points_2.php?s=' . (($display * ($i - 1))) .
'&np=' . $num_pages . '&sort=' . $sort .'">' . $i . '</a> ';
} else {
echo $i . ' ';
}
}
// If it's not the last page, make a Next button.
if ($current_page != $num_pages) {
echo '<a href="view_points_2.php?s=' . ($start + $display) . '&np=' .
$num_pages . '&sort=' . $sort .'">Next</a> ';
}
echo '</p>';
} // End of links section.
?>
<br class="clearboth" />
</div>
</div>
</div>
<?php
include ('./includes/footer_admin_user.html'); // Include the HTML footer.
?>

You would need to do:
$row = #mysql_fetch_array ($result, MYSQL_NUM);
on the line before the error.
Right now it is throwing you an error because the last time you set $row was in this piece of code on the top:
// Count the number of records
$query = "SELECT COUNT(*) FROM tally_point, users WHERE tally_point.users_id = users.users_id ORDER BY tally_points_entry_date DESC";
$result = #mysql_query ($query);
$row = #mysql_fetch_array ($result, MYSQL_NUM);
In this context $row only has one element ($row[0]).

Related

PHP if statement - Resource id issue

I have some code below which retrieves data from a table named "tally_point"
What I am trying to is retrieve a value from a column named 'tpt_id'
On another table, there is a table named "tally_point_type", which has has the primary key 'tpt_id' as well.
What I am trying to do is get the 'tpt_name' value to print from the tally_point_type row. At the moment I can get the "Order Details" link to work but the $tpt_name value prints out a Resource id# value.
I knwo Im close but can't quite figure out how to get this to work.
<?php
$pointstype = $row['tpt_id'];
$type = '<td align="center">';
if($pointstype > '0') {
$query = "SELECT tpt_name
FROM tally_point_type
WHERE'" . $row['tpt_id'] . "'=$pointstype";
$tpt_name = mysql_query($query);
$type .='<strong>' . $tpt_name . '</strong></td></tr>';
}
else {
$type .='<strong>Order Details</strong></td></tr>';
}
echo $type;
?>
Full code here:
<?php # index.php
require_once ('./includes/config.inc.php');
$page_title = 'Title';
include ('includes/header.html');
if (!isset($_SESSION['admin_int_id'])) {
$url = 'http://' . $_SERVER['HTTP_HOST']
. dirname($_SERVER['PHP_SELF']);
// Check for a trailing slash.
if ((substr($url, -1) == '/') OR (substr($url, -1) == '\\') ) {
$url = substr ($url, 0, -1); // Chop off the slash.
}
$url .= '/login.php';
ob_end_clean(); // Delete the buffer.
header("Location: $url");
exit(); // Quit the script.
}
if ( (isset($_GET['id'])) && (is_numeric($_GET['id'])) )
{ // Accessed through view_users.php
$id = $_GET['id'];
} elseif ( (isset($_POST['id'])) && (is_numeric($_POST['id'])) )
{ // Form has been submitted.
$id = $_POST['id'];
} else { // No valid ID, kill the script.
echo '<h1 id="mainhead">Page Error</h1>
<p class="error">This page has been accessed in error.</p><p><br /><br /></p>';
include ('./includes/header.html');
exit();
}
require_once ('/database.php'); // Connect to the db.
$display = 1000;
if (isset($_GET['np'])) { // Already been determined.
$num_pages = $_GET['np'];
} else { // Need to determine.
$query = "SELECT COUNT(*) FROM tally_point, users WHERE tally_point.users_id = users.users_id ORDER BY tally_points_entry_date DESC";
$result = #mysql_query ($query);
$row = #mysql_fetch_array ($result, MYSQL_NUM);
$num_records = $row[0];
if ($num_records > $display) { // More than 1 page.
$num_pages = ceil($num_records/$display);
} else {
$num_pages = 1;
}
}
if (isset($_GET['s'])) {
$start = $_GET['s'];
} else {
$start = 0;
}
$link1 = "{$_SERVER['PHP_SELF']}?sort=lna";
$link2 = "{$_SERVER['PHP_SELF']}?sort=fna";
$link3 = "{$_SERVER['PHP_SELF']}?sort=dra";
if (isset($_GET['sort'])) {
switch ($_GET['sort']) {
case 'lna':
$order_by = 'tally_points_in ASC';
$link1 = "{$_SERVER['PHP_SELF']}?sort=lnd";
break;
case 'lnd':
$order_by = 'tally_points_in DESC';
$link1 = "{$_SERVER['PHP_SELF']}?sort=lna";
break;
case 'fna':
$order_by = 'total ASC';
$link2 = "{$_SERVER['PHP_SELF']}?sort=fnd";
break;
case 'fnd':
$order_by = 'total DESC';
$link2 = "{$_SERVER['PHP_SELF']}?sort=fna";
break;
case 'dra':
$order_by = 'tally_points_entry_date ASC';
$link3 = "{$_SERVER['PHP_SELF']}?sort=drd";
break;
case 'drd':
$order_by = 'tally_points_entry_date DESC';
$link3 = "{$_SERVER['PHP_SELF']}?sort=dra";
break;
default:
$order_by = 'tally_points_entry_date DESC';
break;
}
$sort = $_GET['sort'];
} else { // Use the default sorting order.
$order_by = 'tally_points_entry_date DESC';
$sort = 'dra';
}
$query = "SELECT ta.tally_points_in, ta.order_id, ta.total, ta.tpt_id , DATE_FORMAT(ta.tally_points_entry_date, '%d-%m-%Y') AS dr, ta.users_id
FROM tally_point AS ta
WHERE ta.users_id=$id
ORDER BY
".$order_by." LIMIT ".$start.", ".$display;
$result = #mysql_query ($query); // Run the query.
echo '
<table width="500" cellspacing="1" cellpadding="7">
<tr class="top">
<td align="left"><b>Date</b></td>
<td align="center"><b>Credit</b></td>
<td align="center"><b>Debit</b></td>
<td align="center"><b>Description</b></td>
</tr>
';
$bg = '#ffffff'; // Set the background color.
while ($row = mysql_fetch_array($result, MYSQL_ASSOC)) {
$pointsitem = $row['order_id'];
$pointstype = $row['tpt_id'];
$bg = ($bg=='#eaeced' ? '#ffffff' : '#eaeced'); // Switch the background color.
//$entries = floor($row['ltd_entry_amount']/200);
echo '<tr bgcolor="' . $bg . '">';
echo '<td align="left">' . $row['dr'] . '</td>';
echo '<td align="center"><strong>' . $row['tally_points_in'] . '</strong></td> ';
echo '<td align="center">' . $row['total'] . '</td>';
$type = '<td align="center">';
if($pointstype > '0') {
$query = "SELECT tpt_name
FROM tally_point_type
WHERE'" . $row['tpt_id'] . "'=$pointstype"; //THIS ALSO SEEMS WRONG column name should have backticks if you're trying to escape it and maybe value should be quoted? Also these values are the same, no?
$result = mysql_query($query);
$tpt_name = mysql_fetch_assoc($result);
$type .='<strong>' . $tpt_name['tpt_name'] . '</strong></td></tr>';
} else {
$type .='<strong>Order Details</strong></td></tr>';
}
echo $type;
}
echo '</table>';
mysql_free_result ($result); // Free up the resources.
mysql_close(); // Close the database connection.
if ($num_pages > 1) {
echo '<br /><p>';
$current_page = ($start/$display) + 1;
if ($current_page != 1) {
echo '<a href="view_points_2.php?s=' . ($start - $display) . '&np=' .
$num_pages . '&sort=' . $sort .'">Previous</a> ';
}
for ($i = 1; $i <= $num_pages; $i++) {
if ($i != $current_page) {
echo '<a href="view_points_2.php?s=' . (($display * ($i - 1))) .
'&np=' . $num_pages . '&sort=' . $sort .'">' . $i . '</a> ';
} else {
echo $i . ' ';
}
}
if ($current_page != $num_pages) {
echo '<a href="view_points_2.php?s=' . ($start + $display) . '&np=' .
$num_pages . '&sort=' . $sort .'">Next</a> ';
}
echo '</p>';
}
include ('./includes/footer.html'); // Include the HTML footer.
?>
You need to fetch the result.
<?php
$pointstype = $row['tpt_id'];
$type = '<td align="center">';
if($pointstype > '0') {
$query = "SELECT tpt_name
FROM tally_point_type
WHERE'" . $row['tpt_id'] . "'=$pointstype"; //THIS ALSO SEEMS WRONG column name should have backticks if you're trying to escape it and maybe value should be quoted? Also these values are the same, no?
$result = mysql_query($query);
$tpt_name = mysql_fetch_assoc($result);
$type .='<strong>' . $tpt_name['tpt_name'] . '</strong></td></tr>';
} else {
$type .='<strong>Order Details</strong></td></tr>';
}
echo $type;
?>
Also see notes in the comment of your query, consider switching drivers to mysqli or PDO, and I'm not sure about where the data you're using is coming from but might be open to a SQL injection. How can I prevent SQL injection in PHP?
Here's the manual link for future reference http://php.net/manual/en/function.mysql-query.php. See example #2.
You need to fetch the result:
$result = mysql_query($query);
$row = mysql_fetch_assoc($result);
$tpt_name = $row['tpt_name'];

"Next" button doesn't refresh page with next 25 results

I have the code below and am trying to get the next 25 results from my sql table to appear on page. However, whenever I click the next button, no information is displayed. I have my offset = ($page - 1) * $items_per_page......I'm struggling to figure this out as it seems so simple compared the other code I've written, but is proving to be very elusive to me....any assistance would be greatly appreciated. My primary issue is that the next link does not provide the next 25 results and I'm unable to determine why and how to correct.
echo "<h3 style='text-align:center;'>Welcome to the Exchange Portal, " . $row['name'] . "! </h3>";
$items_per_page = 25;
$sql_count = "SELECT pin, title, title2, email, phone FROM crown_acura";
$result_cnt = mysqli_query($conn, $sql_count);
if(false === $result_cnt) {
throw new Exception('Query failed with: ' . mysqli_error());
} else {
$row_count = mysqli_num_rows($result_cnt);
// free the result set as you don't need it anymore
//mysqli_free_result($result_cnt);
}
echo $row_count;
echo " ";
if (!isset($_GET['Page'])) {
$Page = 1;
} else {
$Page = $_GET['Page'];
}
echo $page;
echo " ";
$page_count = 0;
if (0 === $row_count) {
// maybe show some error since there is nothing in your table
} else {
// determine page_count
$page_count = (int)ceil($row_count / $items_per_page);
// double check that request page is in range
if($page > $page_count) {
// error to user, maybe set page to 1
$page = 1;
}
}
echo " ";
echo $page_count;
echo " ";
echo $items_per_page;
$offset = ($page-1)*$items_per_page;
//echo $paging_info;
//echo " ";
echo "<br />";
//Query for displaying results
$list_sql = "SELECT pin, title, title2, email, phone FROM crown_acura LIMIT $offset, $items_per_page";
$result_query = $conn->query($list_sql);
//Table for displaying query results
echo "<table class='verify'>";
echo "<tr >";
echo "<td><h3>Name</h3></td><td> </td><td><h3>E-mail</h3></td><td><h3>Phone</h3></td>";
echo "</tr>";
for($i = 1; $i<= $page_count; $i++) {
if ($result_query->num_rows > 0) {
// output data of each row
while($row3 = mysqli_fetch_array($result_query)) {
echo "<tr>";
echo "<td class='dltd2 dlcl'>" . $row3["title"] . "</td><td>" . $row3["title2"] . "</td><td><a href='mailto:" . $row3['email'] . "'>" . $row3["email"] . "</a> </td><td>" . $row3["phone"] . " </td>";
echo "</tr>";
}
} else {
echo "0 results";
}
}
echo "<tr></tr>";
$next_page = $page + 1;
$last_page = $page - 1;
if($paging_info['curr_page'] <= 1) {
echo "<tr>";
echo "<td></td><td colspan='2'><a class='loadlink' href='" . $_PHP_SELF . "'>Next 25</a></td><td></td>";
echo "</tr>";
} elseif ($paging_info['curr_page'] < $page_count) {
echo "<tr>";
echo "<td></td><td><a href='" . $_PHP_SELF . "?page=" . $last_page . "'>Prev 25</a></td><td><a href='" . $_PHP_SELF . "?page=" . $next_page . "'>Next 25</a></td><td></td>";
echo "</tr>";
} elseif ($paging_info['curr_page'] === $page_count) {
echo "<tr>";
echo "<td></td><td colspan='2'><a href='" . $_PHP_SELF . "?page=" . $last_page . "'>Prev 25</a></td><td></td>";
echo "</tr>";
}
echo "</table>";
}
}
}
Have you tried to run the rendered SQL.
Output to browser:
"SELECT pin, title, title2, email, phone FROM crown_acura LIMIT $offset, $items_per_page"
try this... and change $page for different values (2,3,...,etc)
<?php
$items_per_page = 25;
$sql_count = "SELECT pin, title, title2, email, phone FROM crown_acura";
$result_cnt = mysqli_query($conn, $sql_count);
if (false === $result_cnt) {
throw new Exception('Query failed with: ' . mysqli_error());
} else {
$row_count = mysqli_num_rows($result_cnt);
// free the result set as you don't need it anymore
//mysqli_free_result($result_cnt);
}
echo $row_count;
echo " ";
if (!isset($_GET['Page'])) {
$Page = 1;
} else {
$Page = $_GET['Page'];
}
echo $page;
echo " ";
$page_count = 0;
if (0 === $row_count) {
// maybe show some error since there is nothing in your table
} else {
// determine page_count
$page_count = (int)ceil($row_count / $items_per_page);
// double check that request page is in range
if ($page > $page_count) {
// error to user, maybe set page to 1
$page = 1;
}
}
echo " ";
echo $page_count;
echo " ";
echo $items_per_page;
$offset = ($page - 1) * $items_per_page;
//echo $paging_info;
//echo " ";
echo "<br />";
//Query for displaying results
$list_sql = "SELECT pin, title, title2, email, phone FROM crown_acura LIMIT $offset, $items_per_page";
$result_query = $conn->query($list_sql);
echo ("RESULTS: ".$result_query->num_rows());
?>

PHP Pagination code not working

I am unable to do pagination. The code display all the data retrieve from the mysql. Please help me to get it right.....
function.php
function pagination($limit=5) //here limit is not taken by the code
{
//$limit=5; if I uncomment this line limit will work
global $admin;
$sql = "SELECT FOUND_ROWS();";
$result = mysql_query($sql) or die(mysql_error());
$row = mysql_fetch_array($result);
$numrows = $row[0];
$pagelinks = "<div class=pagelinks>";
if ($numrows > $limit) {
if(isset($_GET['page'])){
$page = $_GET['page'];
} else {
$page = 1;
}
$currpage = $_SERVER['PHP_SELF'] . "?" . $_SERVER['QUERY_STRING'];
$currpage = str_replace("&page=".$page,"",$currpage);
if($page == 1){
$pagelinks .= "<span class='pageprevdead'>< PREV</span>";
}else{
$pageprev = $page - 1;
$pagelinks .= "<a class='pageprevlink' href='" . $currpage .
"&page=" . $pageprev . "'>< PREV</a>";
}
$numofpages = ceil($numrows / $limit);
$range = $admin['pageRange']['value'];
if ($range == "" or $range == 0) $range = 7;
$lrange = max(1,$page-(($range-1)/2));
$rrange = min($numofpages,$page+(($range-1)/2));
if (($rrange - $lrange) < ($range - 1)) {
if ($lrange == 1) {
$rrange = min($lrange + ($range-1), $numofpages);
} else {
$lrange = max($rrange - ($range-1), 0);
}
}
if ($lrange > 1) {
$pagelinks .= "..";
} else {
$pagelinks .= " ";
}
for($i = 1; $i <= $numofpages; $i++){
if($i == $page){
$pagelinks .= "<span class='pagenumdead'>$i</span>";
}else{
if ($lrange <= $i and $i <= $rrange) {
$pagelinks .= "<a class='pagenumlink' href='" . $currpage .
"&page=" . $i . "'>" . $i . "</a>";
}
}
}
if ($rrange < $numofpages) {
$pagelinks .= "..";
} else {
$pagelinks .= " ";
}
if(($numrows - ($limit * $page)) > 0){
$pagenext = $page + 1;
$pagelinks .= "<a class='pagenextlink' href='" . $currpage .
"&page=" . $pagenext . "'>NEXT ></a>";
} else {
$pagelinks .= "<span class='pagenextdead'>NEXT ></span>";
}
} else {
$pagelinks .= "<span class='pageprevdead'>
< PREV</span> ";
$pagelinks .= "<span class='pagenextdead'>
NEXT ></span> ";
}
$pagelinks .= "</div>";
return $pagelinks;
}'
index.php
$sql = "SELECT id FROM articles WHERE is_published=1 " .
"ORDER BY date_published DESC"; //this is the query to retrive data from mysql
$result = mysql_query($sql,$conn);
if (mysql_num_rows($result) == 0) {
echo " <br />\n";
echo " There are currently no articles to view.\n";
} else {
while ($row = mysql_fetch_array($result)) {
outputStory($row['article_id'],TRUE);
}
}
echo pagination($limit);`
This code is incomplete. However the first thing you need to do is add the $limit to the actual sql query:
$sql = "SELECT id FROM articles WHERE is_published=1 " .
"ORDER BY date_published DESC LIMIT {$limit}";
Try this.
Just create a mysql table called players with 3 fields:- id, firstname, lastname to check how the code is working.
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN""http://www.w3.org/TR/html4/strict.dtd">
<html>
<head>
<title>View Records</title>
</head>
<body>
<?php
/*
VIEW-PAGINATED.PHP
Displays all data from 'players' table
This is a modified version of view.php that includes pagination
*/
// connect to the database
include('dbconfig.php');
// number of results to show per page
$per_page = 2;
// figure out the total pages in the database
$result = mysql_query("SELECT * FROM players");
$total_results = mysql_num_rows($result);
$total_pages = ceil($total_results / $per_page);
// check if the 'page' variable is set in the URL (ex: view-paginated.php?page=1)
if (isset($_GET['page']) && is_numeric($_GET['page']))
{
$show_page = $_GET['page'];
// make sure the $show_page value is valid
if ($show_page > 0 && $show_page <= $total_pages)
{
$start = ($show_page -1) * $per_page;
$end = $start + $per_page;
}
else
{
// error - show first set of results
$start = 0;
$end = $per_page;
}
}
else
{
// if page isn't set, show first set of results
$start = 0;
$end = $per_page;
}
// display pagination
echo "<p><a href='view.php'>View All</a> | <b>View Page:</b> ";
for ($i = 1; $i <= $total_pages; $i++)
{
echo "<a href='view-paginated.php?page=$i'>$i</a> ";
}
echo "</p>";
// display data in table
echo "<table border='1' cellpadding='10'>";
echo "<tr> <th>ID</th> <th>First Name</th> <th>Last Name</th> <th></th> <th></th></tr>";
// loop through results of database query, displaying them in the table
for ($i = $start; $i < $end; $i++)
{
// make sure that PHP doesn't try to show results that don't exist
if ($i == $total_results) { break; }
// echo out the contents of each row into a table
echo "<tr>";
echo '<td>' . mysql_result($result, $i, 'id') . '</td>';
echo '<td>' . mysql_result($result, $i, 'firstname') . '</td>';
echo '<td>' . mysql_result($result, $i, 'lastname') . '</td>';
echo '<td>Edit</td>';
echo '<td>Delete</td>';
echo "</tr>";
}
// close table>
echo "</table>";
// pagination
?>
<p>Add a new record</p>
</body>
</html>

How to just show few lines from a whole blog-post on a certain page?

I am making a blog in which I want to show just the summary of all posts on the home page rather than whole posts.
Below is the function that I use to get the posts on my home page.
function get_content($id = '')
{
if ($id != ""):
$id = mysql_real_escape_string($id);
$sql = "SELECT * from cms_content WHERE id = '$id'";
$return = '<p>Go back to Home page</p>';
echo $return;
else:
$sql = "select * from cms_content ORDER BY id DESC";
endif;
$res = mysql_query($sql) or die(mysql_error());
if (mysql_num_rows($res) != 0):
while ($row = mysql_fetch_assoc($res)) {
echo '<h1>' . $row['title'] . '</h1>';
echo '<p>' . "by: " . $row['author'] . ", posted on: " . $row['date'] . '<p>';
echo '<p>' . $row['body'] . '</p><br />';
}
else:
echo '<p>We are really very sorry, this page does not exist!</p>';
endif;
}
And then simply I use this php code to get the posts:
<?php
if (isset($_GET['id'])) :
$obj->get_content($_GET['id']);
else :
$obj->get_content();
endif;
?>
So how to get the summary only using php function or mysql as I know that we can use mysql query to get limit the words?
function sumarize($your_string, $limit_lines){
$count = 0;
foreach(explode("\n", $your_string) as $line){
$count++;
echo $line."\n";
if ($count == $limit_lines) break;
}
}
sumarize($row['body'], 10);
will show first ten lines
1-lined:
echo '<p>'.implode("\n",array_slice(explode("\n",$row['body']),0,10)).'</p>';
instead of line with $row['body']

SELECT query for selecting logged in users rows only - PHP/MySQL

I have a members only website in which the logged in users fill in an entry form which goes to a MySQL table called 'ltd_sales_list' with the following columns:
ltd_item_id | ltd_user_id |
ltd_invoice_no | ltd_entry_amount |
ltd_entry_date
For each new entry they input, a new id/primary key is generated ('ltd_item_id') for each row, while their SESSION log in id is recorded in 'ltd_user_id' while the 'ltd_entry_date' is a timestamp. The entry form page works fine but viewing the entry data is where I am having the issue.
I have put together the code below called view-list.php but this calls up every user's entry list. What I am trying to do is show the logged in user's entry list only.
I think the answer lies within the queries somewhere and have tried some WHERE statements with ltd_user_id = $_SESSION['ltd_user_id'] and similar but for no success.
If anyone could help or could point me to some links that would be greatly appreciated!
<?php
require_once ('./includes/config.inc.php');
$page_title = 'Page Title';
include ('./includes/header.html');
if (!isset($_SESSION['ltd_user_id'])) {
$url = 'http://' . $_SERVER['HTTP_HOST']
. dirname($_SERVER['PHP_SELF']);
if ((substr($url, -1) == '/') OR (substr($url, -1) == '\\') ) {
$url = substr ($url, 0, -1);
}
$url .= '/login.php';
ob_end_clean();
header("Location: $url");
exit();
}
?>
<div id="">HTML Content HERE</div>
<?php
echo '<h1>My Entry Log</h1>';
require_once ('/server/database_connection.php'); // Connect to the db.
$display = 10;
if (isset($_GET['np'])) {
$num_pages = $_GET['np'];
} else {
$query = "SELECT COUNT(*) FROM ltd_sales_list ORDER BY ltd_entry_date DESC";
$result = #mysql_query ($query);
$row = mysql_fetch_array ($result, MYSQL_NUM);
$num_records = $row[0];
if ($num_records > $display) {
$num_pages = ceil ($num_records/$display);
} else {
$num_pages = 1;
}
}
if (isset($_GET['s'])) {
$start = $_GET['s'];
} else {
$start = 0;
}
$link1 = "{$_SERVER['PHP_SELF']}?sort=lna";
$link2 = "{$_SERVER['PHP_SELF']}?sort=fna";
$link3 = "{$_SERVER['PHP_SELF']}?sort=dra";
if (isset($_GET['sort'])) {
switch ($_GET['sort']) {
case 'lna':
$order_by = 'ltd_invoice_no ASC';
$link1 = "{$_SERVER['PHP_SELF']}?sort=lnd";
break;
case 'lnd':
$order_by = 'ltd_invoice_no DESC';
$link1 = "{$_SERVER['PHP_SELF']}?sort=lna";
break;
case 'fna':
$order_by = 'ltd_entry_amount ASC';
$link2 = "{$_SERVER['PHP_SELF']}?sort=fnd";
break;
case 'fnd':
$order_by = 'ltd_entry_amount DESC';
$link2 = "{$_SERVER['PHP_SELF']}?sort=fna";
break;
case 'dra':
$order_by = 'ltd_entry_date ASC';
$link3 = "{$_SERVER['PHP_SELF']}?sort=drd";
break;
case 'drd':
$order_by = 'ltd_entry_date DESC';
$link3 = "{$_SERVER['PHP_SELF']}?sort=dra";
break;
default:
$order_by = 'ltd_entry_date DESC';
break;
}
$sort = $_GET['sort'];
} else {
$order_by = 'ltd_entry_date DESC';
$sort = 'dra';
}
$query = "SELECT ltd_invoice_no, ltd_entry_amount,
DATE_FORMAT(ltd_entry_date, '%M %d, %Y') AS dr, ltd_user_id FROM ltd_sales_list ORDER BY
$order_by LIMIT $start, $display";
$result = #mysql_query ($query);
echo '<table width="520" cellspacing="1" cellpadding="11">
<tr>
<td align="left"><b>Invoice Number</b></td>
<td align="left"><b>Invoice Amount</b></td>
<td align="left"><b>Date Entered</b></td>
</tr>
';
$bg = '#eeeeee';
while ($row = mysql_fetch_array($result, MYSQL_ASSOC)) {
$bg = ($bg=='#eaeced' ? '#ffffff' : '#eaeced');
echo '<tr bgcolor="' . $bg . '">
<td align="left">' . $row['ltd_invoice_no'] . '</td>
<td align="left">' . $row['ltd_entry_amount'] . '</td>
<td align="left">' . $row['dr'] . '</td>
</tr>
';
}
echo '</table>';
mysql_free_result ($result);
mysql_close();
if ($num_pages > 1) {
echo '<br /><p>';
$current_page = ($start/$display) + 1;
if ($current_page != 1) {
echo '<a href="view-list.php?s=' . ($start - $display) . '&np=' .
$num_pages . '&sort=' . $sort .'">Previous</a> ';
}
for ($i = 1; $i <= $num_pages; $i++) {
if ($i != $current_page) {
echo '<a href="view-list.php?s=' . (($display * ($i - 1))) .
'&np=' . $num_pages . '&sort=' . $sort .'">' . $i . '</a> ';
} else {
echo $i . ' ';
}
}
if ($current_page != $num_pages) {
echo '<a href="view-list.php?s=' . ($start + $display) . '&np=' .
$num_pages . '&sort=' . $sort .'">Next</a> ';
}
echo '</p>';
}
?>
<div id="">HTML Content HERE</div>
<?php
include ('./includes/footer.html');
?>
Cheers
Adam
Could it be as simple as escaping everything, exiting from the quotes when doing variables? It looks to me like it should work. Can you vardump the $_SESSION['ltd_user_id'] somewhere to make sure it is behaving as expected?
$query = "SELECT `ltd_invoice_no`, `ltd_entry_amount`,
DATE_FORMAT(`ltd_entry_date`, '%M %d, %Y') AS `dr`, `ltd_user_id` FROM `ltd_sales_list` WHERE `ltd_user_id` = '".$_SESSION['ltd_user_id']."' ORDER BY
".$order_by." LIMIT ".$start.", ".$display;

Categories