0

I've got a script that shows the results of SQL command "SELECT" in pages that have an error for $_PHP_SELF constant used in it:

<html>
    <head>
        <title>Paging Using PHP</title>
    </head>
<body>
<?php
$dbhost = '127.0.0.1';
$dbuser = 'guest';
$dbpass = 'guest123';
$rec_limit = 10;
$conn = mysql_connect($dbhost, $dbuser, $dbpass);
if(! $conn ) {
    die('Could not connect: ' . mysql_error());
}
mysql_select_db('test_db');
/* Get total number of records */
$sql = "SELECT count(emp_id) FROM employee ";
$retval = mysql_query( $sql, $conn );
if(! $retval ) {
    die('Could not get data: ' . mysql_error());
}
$row = mysql_fetch_array($retval, MYSQL_NUM );
$rec_count = $row[0];
if( isset($_GET{'page'} ) ) {
    $page = $_GET{'page'} + 1;
    $offset = $rec_limit * $page ;
}else {
    $page = 0;
    $offset = 0;
}
$left_rec = $rec_count -($page * $rec_limit);
$sql = "SELECT emp_id, emp_name, emp_salary ". 
"FROM employee "."LIMIT $offset, $rec_limit";
$retval = mysql_query( $sql, $conn );
if(! $retval ) {
    die('Could not get data: ' . mysql_error());
}
while($row = mysql_fetch_array($retval, MYSQL_ASSOC)) {
    echo "EMP ID :{$row['emp_id']}  <br> ".
       "EMP NAME : {$row['emp_name']} <br> ".
       "EMP SALARY : {$row['emp_salary']} <br> ".
       "--------------------------------<br>";
}
if( $page > 0 ) {
    $last = $page -2;
    echo "<a href = \"$_PHP_SELF?page = $last\">Last 10 Records</a> |";
    echo "<a href = \"$_PHP_SELF?page = $page\">Next 10 Records</a>";
}else if( $page == 0 ) {
    echo "<a href = \"$_PHP_SELF?page = $page\">Next 10 Records</a>";
}else if( $left_rec < $rec_limit ) {
    $last = $page -2;
    echo "<a href = \"$_PHP_SELF?page = $last\">Last 10 Records</a>";
}
mysql_close($conn);
?>
</body>

I've seen a lot of answers that couldn't help me with this subject like:

$PHP_SELF = &$_SERVER['PHP_SELF'];
echo $PHP_SELF;

How to make the script working correctly?

It should show only 10 results in each page, and go to the next page for the next 10 result by clicking the hyperlink in the bottom of the page.

peterh
  • 11,875
  • 18
  • 85
  • 108
arianpress
  • 456
  • 1
  • 6
  • 16

2 Answers2

0
if(isset($_GET["page"]))
{
    $page=$_GET["page"];
    $back=$page-5;
}
else
{
    $page=0;
    $back=0;
}
$forward=$page+5;

while($page<=$back and $page>=$forward)
{
    //code to execute
}

Would something like this work?

echo '<a href="?=' . $page+10 . '">next</a>';
Davie
  • 55
  • 1
  • 8
0

You shouldn't use $_SERVER['PHP_SELF'] in that way. Then PHP_SELF print the complete URL to your page. Its possible to inject code over your page to your site.

PHP_SELF and XSS

if you want to use it please escape all your output.

In your case its enough to use only ?page or write the complete url before the parameters.

echo sprintf('<a href = "?page=%d">Last 10 Records</a> |', $last);
René Höhle
  • 26,716
  • 22
  • 73
  • 82