Pagination not taking value to second page? - php

$today = date('D, d M, Y');
$sql = "SELECT * FROM table WHERE date = '$today'";
if ($_POST!="") {
$mydate = mysql_real_escape_string($_POST['datepicker']);
if ($mydate != "") {
$sql = "SELECT * FROM table WHERE date = '$mydate'";
}
}
$num_results_per_page = 8;
$num_page_links_per_page = 5;
$pg_param = "";
$result=mysql_query($sql);
$row = mysql_fetch_array($result);
pagination($sql, $num_results_per_page, $num_page_links_per_page, $pg_param);
if($pg_error == '')
{
if(mysql_num_rows($pg_result) > 0)
{
while($data = mysql_fetch_assoc($pg_result))
{
echo "";
}
echo "</br>". $pagination_output;
}
else
{
echo "No Data.";
}
}
else
{
echo $pg_error;
}
Pagination is working correctly for select $today. Here pagination is not taking value to second page in the case of select $mydate. If second page of $mydate clicks, again going to $today. ie Second click is not posting $mydate to next page. How can I take the value to second page?
pagination.php
$pg_error = '';
$pg_result = '';
$pagination_output = '';
$max_pages = '';
$page_id = '';
$page_numbers_per_page = '';
$pg_user_param = '';
function pagination($sql, $num_results_per_page, $num_page_links_per_page, $pg_param)
{
global $pg_error, $pg_result, $max_pages, $page_id, $page_numbers_per_page, $pg_user_param;
$user_sql = $sql;
$page_numbers_per_page = $num_page_links_per_page;
$results_per_page = $num_results_per_page;
$pg_user_param = $pg_param;
$all_results = mysql_query($user_sql);
if($all_results)
{
if(empty($all_results))
{
$total_results = 0;
}
else
{
$total_results = mysql_num_rows($all_results);
}
$max_pages = ceil($total_results / $results_per_page);
if(isset($_GET['page_id']))
{
$page_id = (int) $_GET['page_id'];
if($page_id > $max_pages || empty($page_id))
{
$page_id = 1;
}
}
else
{
$page_id = 1;
}
$page_id_temp = ($page_id - 1) * $results_per_page;
$sql_offset = $page_id_temp;
$user_sql .= " limit $sql_offset, $results_per_page";
$pg_result = mysql_query($user_sql);
Create_Links();
}
else
{
$pg_error = 'Error with the sql query you entered: '.mysql_error();
}
}
function Create_Links()
{
global $pagination_output, $max_pages, $page_id, $page_numbers_per_page, $pg_user_param;
$pg_page_name = htmlspecialchars($_SERVER['PHP_SELF'] );
if($max_pages > 1)
{
if($page_id > 1)
{
$first_link = 'First ';
}
if($page_id < $max_pages)
{
$last_link = 'Last ';
}
$pre_id = $page_id - 1;
if($pre_id != 0)
{
$pre_link = 'Previous ';
}
$next_id = $page_id + 1;
if($next_id <= $max_pages)
{
$next_link = 'Next ';
}
if($page_id >= $page_numbers_per_page)
{
$start_point = ($page_id - $page_numbers_per_page) + 2;
}
else
{
$start_point = 1;
}
$loop_num = ($start_point + $page_numbers_per_page) - 1;
if($loop_num > $max_pages)
{
$loop_num = $max_pages;
}
$pagination_output = '<div class="pagination"> ';
$pagination_output .= $first_link;
$pagination_output .= $pre_link;
for($i = $start_point; $i <= $loop_num; $i++)
{
if($i == $page_id)
{
$pagination_output .= '<a class="current">'.$i.'</a> ';
}
else
{
$pagination_output .= ''.$i.' ';
}
}
$pagination_output .= $next_link;
$pagination_output .= $last_link;
$pagination_output .= '</div><br />';
}
}
?>

function pagination in your code is not returning the resulting mysql query resource, and your code is not receiving that from the pagination function call
you need
to add return $pg_result; in your pagination function
and add $result=pagination(....
Edit:
Sorry, I noticed you added pg_result to global, which does not need return and the solution I said, but you don't need mysql_query and fetch before that and I don't see where you print the results. there is only echo "", you can try the one I edited last, and see if it works for you.
Edit:
$today = date('D, d M, Y');
$sql = "SELECT * FROM table WHERE date = '$today'";
if ($_POST!="") {
$mydate = mysql_real_escape_string($_POST['datepicker']);
if ($mydate != "") {
$sql = "SELECT * FROM table WHERE date = '$mydate'";
}
}
$num_results_per_page = 8;
$num_page_links_per_page = 5;
$pg_param = "";
//$result=mysql_query($sql);
$pg_result=pagination($sql, $num_results_per_page, $num_page_links_per_page, $pg_param);
if($pg_error == '' && is_resource($pg_result))
{
if(mysql_num_rows($pg_result) > 0)
{
while($data = mysql_fetch_assoc($pg_result))
{
var_dump($data);
}
echo "</br>". $pagination_output;
}
else
{
echo "No Data.";
}
}
else
{
echo $pg_error;
}
pagination.php
$pg_error = '';
$pg_result = '';
$pagination_output = '';
$max_pages = '';
$page_id = '';
$page_numbers_per_page = '';
$pg_user_param = '';
function pagination($sql, $num_results_per_page, $num_page_links_per_page, $pg_param)
{
global $pg_error, $pg_result, $max_pages, $page_id, $page_numbers_per_page, $pg_user_param;
$user_sql = $sql;
$page_numbers_per_page = $num_page_links_per_page;
$results_per_page = $num_results_per_page;
$pg_user_param = $pg_param;
$all_results = mysql_query($user_sql);
if($all_results)
{
if(empty($all_results))
{
$total_results = 0;
}
else
{
$total_results = mysql_num_rows($all_results);
}
$max_pages = ceil($total_results / $results_per_page);
if(isset($_GET['page_id']))
{
$page_id = (int) $_GET['page_id'];
if($page_id > $max_pages || empty($page_id))
{
$page_id = 1;
}
}
else
{
$page_id = 1;
}
$page_id_temp = ($page_id - 1) * $results_per_page;
$sql_offset = $page_id_temp;
$user_sql .= " limit $sql_offset, $results_per_page";
$pg_result = mysql_query($user_sql);
Create_Links();
return $pg_result;
}
else
{
$pg_error = 'Error with the sql query you entered: '.mysql_error();
}
}
function Create_Links()
{
global $pagination_output, $max_pages, $page_id, $page_numbers_per_page, $pg_user_param;
$pg_page_name = htmlspecialchars($_SERVER['PHP_SELF'] );
if($max_pages > 1)
{
if($page_id > 1)
{
$first_link = 'First ';
}
if($page_id < $max_pages)
{
$last_link = 'Last ';
}
$pre_id = $page_id - 1;
if($pre_id != 0)
{
$pre_link = 'Previous ';
}
$next_id = $page_id + 1;
if($next_id <= $max_pages)
{
$next_link = 'Next ';
}
if($page_id >= $page_numbers_per_page)
{
$start_point = ($page_id - $page_numbers_per_page) + 2;
}
else
{
$start_point = 1;
}
$loop_num = ($start_point + $page_numbers_per_page) - 1;
if($loop_num > $max_pages)
{
$loop_num = $max_pages;
}
$pagination_output = '<div class="pagination"> ';
$pagination_output .= $first_link;
$pagination_output .= $pre_link;
for($i = $start_point; $i <= $loop_num; $i++)
{
if($i == $page_id)
{
$pagination_output .= '<a class="current">'.$i.'</a> ';
}
else
{
$pagination_output .= ''.$i.' ';
}
}
$pagination_output .= $next_link;
$pagination_output .= $last_link;
$pagination_output .= '</div><br />';
}
}
?>

Looks like you're mixing up the concept of $_POST and $_GET.
By having your pagination links point to '<a href="'.$pg_page_name.'?page_id='.$i . $pg_user_param.'"... You should be intercepting $_GET['page_id'] before you make your SQL query.
Your top code references $_POST['datepicker'] but you don't mention a form anywhere and your pagination links certainly aren't posting that data in your example.

You should use $pg_param = ""; to pass your own query parameters. Ex: &date=$date_value:
$pg_param = "&date=$date_value";

Related

PHP - Search with Pagination

So I have these two PHP files products.php and receive.php .
What my problem is I want to use Ajax on displaying the products with search and paginates also. The code below works though but only if I use a GET. Is it possible to submit only the page number and refreshes only the div (where products loop) and not the whole page so that my POST requests (from search values - title, keywords) will still hold? coz if I use GET on pagination, the POST requests are getting empty after clicking the second page.
receive.php
$pdo_sql = 'SELECT * FROM items WHERE item_title LIKE %$keyword% OR keywords LIKE %$keyword% ORDER BY id DESC ';
/*** Pagination Code starts ***/
$per_page_html = '';
$page = 1;
$start=0;
// Get Page Number
if(!empty($_GET["page"])) {
$page = $_GET["page"];
$start=($page-1) * ROW_PER_PAGE;
}
// Adds Limit to Query then Execute
$limit=" LIMIT " . $start . "," . ROW_PER_PAGE;
$pagination_statement = $pdo_conn->prepare($pdo_sql);
$pagination_statement->bindValue(':keyword', '%' . $keyword . '%', PDO::PARAM_STR);
$pagination_statement->execute();
// Count the total number of rows
$row_count = $pagination_statement->rowCount();
if(!empty($row_count)){
$total_links=ceil($row_count/ROW_PER_PAGE);
$previous_link = $next_link = $page_link = '';
if($total_links > 4)
{
if($page < 5)
{
for($count = 1; $count <= 5; $count++)
{
$page_array[] = $count;
}
$page_array[] = '...';
$page_array[] = $total_links;
}
else
{
$end_limit = $total_links - 5;
if($page > $end_limit)
{
$page_array[] = 1;
$page_array[] = '...';
for($count = $end_limit; $count <= $total_links; $count++)
{
$page_array[] = $count;
}
}
else
{
$page_array[] = 1;
$page_array[] = '...';
for($count = $page - 1; $count <= $page + 1; $count++)
{
$page_array[] = $count;
}
$page_array[] = '...';
$page_array[] = $total_links;
}
}
}
else
{
for($count = 1; $count <= $total_links; $count++)
{
$page_array[] = $count;
}
}
for($count = 0; $count < count($page_array); $count++)
{
if($page == $page_array[$count])
{
// Current Page = Selected Page
$page_link .= '<a class="paginate_current" href="javascript:void(0)">'.$page_array[$count].'</a>';
$previous_id = $page_array[$count] - 1;
if($previous_id > 0)
{
// Previous Button Enable
$previous_link = '<a class="paginate_prev" href="products.php?page='.$previous_id.'">Previous</a>';
}
else
{
// Previous Button Disabled
$previous_link = '<a class="paginate_prev-disabled" href="javascript:void(0)">Previous</a>';
}
$next_id = $page_array[$count] + 1;
if($next_id > $total_links)
{
// Next Button Disabled
$next_link = '<a class="paginate_next-disabled" href="javascript:void(0)">Next</a>';
}
else
{
// Next Button Enabled
$next_link = '<a class="paginate_next" href="products.php?page='.$next_id.'">Next</a>';
}
}
else
{
if($page_array[$count] == '...')
{
// Ellipsis
$page_link .= '<a class="paginate_ellipsis" href="javascript:void(0)">...</a>';
}
else
{
// Pages
$page_link .= '<a class="paginate_pages" href="products.php?page='.$page_array[$count].'">'.$page_array[$count].'</a>';
}
}
}
$per_page_html .= '<div class="text-center paginate">';
$per_page_html .= $previous_link . $page_link . $next_link;
$per_page_html .= '</div>';
}
$query = $pdo_sql.$limit;
$pdo_statement = $pdo_conn->prepare($query);
$pdo_statement->bindValue(':keyword', '%' . $keyword . '%', PDO::PARAM_STR);
$pdo_statement->execute();
$pdo_result = $pdo_statement->fetchAll();
products.php
<div class="row">
<div class="col">
<div class="products_container grid" id="refresh">
<?php
if(!empty($pdo_result)) {
foreach($pdo_result as $pdo_row) {
$id = $pdo_row['id'];
$name = $pdo_row['item_title'];
$img = $pdo_row['item_img'];
$price = $pdo_row['item_price'];
$sold = $pdo_row['item_sold'];
$stocks = $pdo_row['stocks'];
$date = $pdo_row['date'];
if ($sold >= $max && $date != date("Y-m-d") ) {
$sort = 'hot';
}else if($date == date("Y-m-d") && $sold <= $max){
$sort = 'new';
}else{
$sort = '';
}
echo '
<div class="product grid-item '.$sort.'">
<div class="product_inner">
<div class="product_image">
<img src="'.$img.'" alt="">
<div class="product_tag">'.$sort.'</div>
</div>
<div class="product_content text-center">
<div class="product_title text-long">'.$name.'</div>
<div class="product_price">₱'.number_format($price).'</div>
<div class="product_button ml-auto mr-auto trans_200">
<button class="product_button ml-auto mr-auto trans_200" id="add2c" data-prod=" '.$id.' " type="button" >add to cart</button>
</div>
</div>
</div>
</div>
';
} //End Foreach Loop
}
else{
echo "no products found";
}
?>
</div>
</div>
</div>
<!-- PAGINATION HERE -->
<?php echo $per_page_html; ?>
Method 1 => Without ajax
You can use the GET method for search value also. and in every pagination link
append the search value too.
for example.
$next_link = '<a class="paginate_next" href="products.php?page='.$next_id.'">Next</a>';
instead of above line use below one.
$next_link = '<a class="paginate_next" href="products.php?page='.$next_id.'&search='.$keyword.'">Next</a>';
Method 2 => using ajax
instead of href use a javascript function like below
$next_link = '<a class="paginate_next" href="#" onclick="paginate_fn(\''.$next_id.'\', \''.$keyword.'\'">Next</a>'
<script>
function paginate_fn(pageID, keyword){
$.ajax({
async: true,
type: 'get', // you can use post also
dataType:'json',
data: {'pageID':pageID, 'keyword': keyword},
url: "paget_name.php", // your page name
success: function (data) {
$('#search-content').html( data['content'] );
},
error: function () {
alert('An Error Occurred!.');
}
});
}
</script>

PHP session variables not persisting on new page after form submission

I have a quiz site which randomly shuffles and puts together multiple choice questions. The correct answers (as well as some other data) are stored in session variables, and the students' answers are sent via POST. On the page that the quiz form submission links to, the correct answers in SESSION are compared to the POST data, and the results of the quiz are displayed. The site used to work just fine, so I have no idea what happened to make it suddenly stop working.
I have checked to see that the session_id is the same on both pages and it is. I have made sure that start_session() is placed appropriately above all the HTML (and have even confirmed it by calling var_dump($_SESSION) on the first and second page, user login variables are displayed, but nothing else).
Here is the code from "startquiz.php" which assembles the quiz form. The session variables in question are just after the end of the "DISPLAY A QUESTION LOOP"
<?php
require_once('appvars.php');
require_once('startsession.php');
require_once('generalauthorize.php');
$page_title = '10 Question Quiz';
require_once('header.php');
require_once('navbar.php');
require_once('connectvars.php');
//=================MySQL HANDLING====================
$dbc = mysqli_connect(DB_HOST, DB_USER, DB_PASSWORD, DB_NAME);
$quizcount = count($_GET);
$content_array = [];
foreach($_GET as $quiz_content){
$quiz_content = $quiz_content . ' = 1';
array_push($content_array, $quiz_content);
}
$where_clause = implode(' OR ', $content_array);
$query = 'SELECT * FROM questionbank WHERE ' . $where_clause;
$data = mysqli_query($dbc, $query);
$questions_found = mysqli_num_rows($data);
mysqli_close($dbc);
//==================MySQL HANDLING=======================
if ($questions_found > 9) {
//==========MAKE A LIST OF POSSIBLE QUESTIONS==================
$possible_questions_array = [];
while ($row = mysqli_fetch_array($data)) {
array_push($possible_questions_array, $row);
}
//==========MAKE A LIST OF POSSIBLE QUESTIONS=================
// ============DECIDE WHICH 10 QUESTIONS TO USE=================
$quiz_array = [];
for($i = 0; $i < 10; $i++) {
$question_bank_count = count($possible_questions_array);
$random_question_number = rand(0, ($question_bank_count - 1));
array_push($quiz_array, $possible_questions_array[$random_question_number]);
array_splice($possible_questions_array, $random_question_number, 1);
}
// ============DECIDE WHICH 10 QUESTIONS TO USE=================
//============CREATE QUESTION META DATA ARRAY=================
$quiz_metadata_array = [];
for ($i = 0; $i < count($quiz_array); $i++) {
$question_holder = $quiz_array[$i];
$metadata_only = array_splice($question_holder, 12);
array_push($quiz_metadata_array, $metadata_only);
}
//============CREATE QUESTION META DATA ARRAY=================
echo '<div class="quiz-container">';
echo '<h2 class="mainpagetitles">Good Luck!</h2>';
echo '<br />';
echo '<form role="form" method="post" action="processquiz.php">';
//==============CREATE ARRAYS TO HOLD QUIZ DATA==========
$correct_answers = [];
$question_prompts = [];
//==============CREATE ARRAYS TO HOLD QUIZ DATA==========
//===============DISPLAY A QUESTION LOOP==================
for($i = 0; $i < (count($quiz_array)); $i++){
array_push($question_prompts, $quiz_array[$i]['question']);
//==================ISOLATE THE ANSWERS===============
$answers_array = [];
array_push($correct_answers, $quiz_array[$i]['answer']);
array_push($answers_array, $quiz_array[$i]['answer']);
array_push($answers_array, $quiz_array[$i]['distractor1']);
array_push($answers_array, $quiz_array[$i]['distractor2']);
array_push($answers_array, $quiz_array[$i]['distractor3']);
//==================ISOLATE THE ANSWERS===============
//=================SCRAMBLE THE ANSWERS==============
$scrambled_array = [];
$answer_count = count($answers_array);
for ($j = 0; $j < $answer_count; $j++) {
$random_answer_number = rand(0, (count($answers_array) - 1));
array_push($scrambled_array, $answers_array[$random_answer_number]);
array_splice($answers_array, $random_answer_number, 1);
}
//=================SCRAMBLE THE ANSWERS==============
//====================CREATE THE HTML=================
echo '<h3>Question ' . ($i + 1) . '.</h3>';
echo '<div class="question-container">';
echo '<p class="question">' . $quiz_array[$i]['question'] . '</p>';
//==============LOOP THROUGH THE SCRAMBLED ANSWERS===========
for($k = 0; $k < (count($scrambled_array)); $k++) {
echo '<label for="' . $i . $k . '" class="answer_choice">' . (chr((65 + $k))) . ': </label>';
echo '<input value="' . $scrambled_array[$k] . '" id="' . $i . $k . '" class="answer_choice" type="radio" name="' . $i . '" required><p class="answer_choice"> ' . $scrambled_array[$k] . '</p><br />';
}
//==============LOOP THROUGH THE SCRAMBLED ANSWERS===========
echo '</div>';
echo '<hr>';
//====================CREATE THE HTML=================
}
//===============DISPLAY A QUESTION LOOP==================
echo '<div class="center">';
$_SESSION['correct_answers'] = $correct_answers;
$_SESSION['question_prompts'] = $question_prompts;
$_SESSION['current_quiz'] = $_GET;
$_SESSION['current_quiz_meta'] = $quiz_metadata_array;
echo session_id();
echo '<button type="submit" class="centered-button">Finished!</button>';
echo '</div>';
echo '</form>';
echo '</div>';
} else {
echo '<div class="quiz-container">';
echo '<h2 class="center">Oh no!</h2>';
echo '<h4 class="center">It looks like there aren\'t enough questions in the database to take a quiz for this category yet!</h4>';
echo '<h4 class="center">Talk to your English teachers about adding some more.</h4>';
echo '<h4 class="center">Sorry about that!</h4><br />';
echo '<a class="main_menu_button" href="quizselect.php"> Okay </a>';
echo '</div>';
}
require_once('bootstrapfooter.php');
?>
And here is the code for the quiz processing page. When I insert a var_dump($_SESSION) on this page I get the login variables that are in session, but nothing else.
<?php
require_once('appvars.php');
require_once('startsession.php');
require_once('generalauthorize.php');
$page_title = 'Quiz Results';
require_once('header.php');
require_once('navbar.php');
require_once('connectvars.php');
//=====HAND OFF CURRENT QUIZ KEYWORDS TO LOCAL VARIABLE AND RESET GLOBAL====
$current_quiz = [];
foreach ($_SESSION['current_quiz'] as $key => $value) {
array_push($current_quiz, $value);
}
$_SESSION['current_quiz'] = "";
//=====HAND OFF CURRENT QUIZ KEYWORDS TO LOCAL VARIABLE AND RESET GLOBAL====
//=======UPDATE THE NUMBER OF THIS QUIZ TYPE TAKEN FOR THE USER ===========
$increment_these_quizzes = [];
for ($i = 0; $i < count($current_quiz); $i++) {
if ($current_quiz[$i] == "english_1_1" || $current_quiz[$i] == "english_1_2") {
if (!in_array('english_1_quiz_taken = english_1_quiz_taken + 1', $increment_these_quizzes)) {
$array_insert = 'english_1_quiz_taken = english_1_quiz_taken + 1';
array_push($increment_these_quizzes, $array_insert);
}
} elseif ($current_quiz[$i] == "english_2ot_1" || $current_quiz[$i] == "english_2ot_2") {
if (!in_array('english_2ot_quiz_taken = english_2ot_quiz_taken + 1', $increment_these_quizzes)) {
$array_insert = 'english_2ot_quiz_taken = english_2ot_quiz_taken + 1';
array_push($increment_these_quizzes, $array_insert);
}
} elseif ($current_quiz[$i] == "english_2pt_1" || $current_quiz[$i] == "english_2pt_2") {
if (!in_array('english_2pt_quiz_taken = english_2pt_quiz_taken + 1', $increment_these_quizzes)) {
$array_insert = 'english_2pt_quiz_taken = english_2pt_quiz_taken + 1';
array_push($increment_these_quizzes, $array_insert);
}
} elseif ($current_quiz[$i] == "english_2sw_1" || $current_quiz[$i] == "english_2sw_2") {
if (!in_array('english_2sw_quiz_taken = english_2sw_quiz_taken + 1', $increment_these_quizzes)) {
$array_insert = 'english_2sw_quiz_taken = english_2sw_quiz_taken + 1';
array_push($increment_these_quizzes, $array_insert);
}
} else {
$array_insert = $current_quiz[$i] . '_quiz_taken = ' . $current_quiz[$i] . '_quiz_taken + 1';
array_push($increment_these_quizzes, $array_insert);
}
}
$increment_this = implode(', ', $increment_these_quizzes);
$increase_quiz_count_query = "UPDATE memberinfo SET $increment_this WHERE user_id = $_SESSION[user_id]";
$dbc = mysqli_connect(DB_HOST, DB_USER, DB_PASSWORD, DB_NAME);
mysqli_query($dbc, $increase_quiz_count_query);
mysqli_close($dbc);
//=======UPDATE THE NUMBER OF THIS QUIZ TYPE TAKEN FOR THE USER ===========
//================GET QUESTION COUNT & SCORE QUIZ===========
$score = 0;
$question_count = count($_SESSION['correct_answers']);
for($i = 0; $i < $question_count; $i++) {
$switch = 0;
$keywords = [];
//==============CORRECT ANSWER HANDLING=====================
if ($_POST[$i] == $_SESSION['correct_answers'][$i]) {
$generic_array = [];
$correct_array = [];
$score++;
foreach ($_SESSION['current_quiz_meta'][$i] as $key => $value) {
if ($switch == 1) {
if ($value == 1) {
if ($key == "english_1_1" || $key == "english_1_2") {
if (!in_array('english_1_correct = english_1_correct + 1', $correct_array)) {
$key = 'english_1_correct = english_1_correct + 1';
array_push($correct_array, $key);
}
if (!in_array('english_1_answers = english_1_answers + 1', $generic_array)) {
$gkey = 'english_1_answers = english_1_answers + 1';
array_push($generic_array, $gkey);
}
} elseif ($key == "english_2ot_1" || $key == "english_2ot_2") {
if (!in_array('english_2ot_correct = english_2ot_correct + 1', $correct_array)) {
$key = 'english_2ot_correct = english_2ot_correct + 1';
array_push($correct_array, $key);
}
if (!in_array('english_2ot_answers = english_2ot_answers + 1', $generic_array)) {
$gkey = 'english_2ot_answers = english_2ot_answers + 1';
array_push($generic_array, $gkey);
}
} elseif ($key == "english_2pt_1" || $key == "english_2pt_2") {
if (!in_array('english_2pt_correct = english_2pt_correct + 1', $correct_array)) {
$key = 'english_2pt_correct = english_2pt_correct + 1';
array_push($correct_array, $key);
}
if (!in_array('english_2pt_answers = english_2pt_answers + 1', $generic_array)) {
$gkey = 'english_2pt_answers = english_2pt_answers + 1';
array_push($generic_array, $gkey);
}
} elseif ($key == "english_2sw_1" || $key == "english_2sw_2") {
if (!in_array('english_2sw_correct = english_2sw_correct + 1', $correct_array)) {
$key = 'english_2sw_correct = english_2sw_correct + 1';
array_push($correct_array, $key);
}
if (!in_array('english_2sw_answers = english_2sw_answers + 1', $generic_array)) {
$gkey = 'english_2sw_answers = english_2sw_answers + 1';
array_push($generic_array, $gkey);
}
} else {
$keyword_generic = $key . '_answers = ' . $key . '_answers + 1';
$keyword_correct = $key . '_correct = ' . $key . '_correct + 1';
array_push($generic_array, $keyword_generic);
array_push($correct_array, $keyword_correct);
}
}
$switch = 0;
} else {
$switch = 1;
}
}
$set_what_generic = implode(', ', $generic_array);
$set_what = implode(', ', $correct_array);
$update_query = "UPDATE memberinfo SET $set_what WHERE user_id = $_SESSION[user_id]";
$update_generic_query = "UPDATE memberinfo SET $set_what_generic WHERE user_id = $_SESSION[user_id]";
$dbc = mysqli_connect(DB_HOST, DB_USER, DB_PASSWORD, DB_NAME);
mysqli_query($dbc, $update_query);
mysqli_query($dbc, $update_generic_query);
mysqli_close($dbc);
//==============CORRECT ANSWER HANDLING=====================
//==============WRONG ANSWER HANDLING=====================
} else {
$generic_array = [];
foreach ($_SESSION['current_quiz_meta'][$i] as $key => $value) {
if ($switch == 1) {
if ($value == 1) {
if ($key == "english_1_1" || $key == "english_1_2") {
if (!in_array('english_1_answers = english_1_answers + 1', $generic_array)) {
$gkey = 'english_1_answers = english_1_answers + 1';
array_push($generic_array, $gkey);
}
} elseif ($key == "english_2ot_1" || $key == "english_2ot_2") {
if (!in_array('english_2ot_answers = english_2ot_answers + 1', $generic_array)) {
$gkey = 'english_2ot_answers = english_2ot_answers + 1';
array_push($generic_array, $gkey);
}
} elseif ($key == "english_2pt_1" || $key == "english_2pt_2") {
if (!in_array('english_2pt_answers = english_2pt_answers + 1', $generic_array)) {
$gkey = 'english_2pt_answers = english_2pt_answers + 1';
array_push($generic_array, $gkey);
}
} elseif ($key == "english_2sw_1" || $key == "english_2sw_2") {
if (!in_array('english_2sw_answers = english_2sw_answers + 1', $generic_array)) {
$gkey = 'english_2sw_answers = english_2sw_answers + 1';
array_push($generic_array, $gkey);
}
} else {
$keyword_generic = $key . '_answers = ' . $key . '_answers + 1';
array_push($generic_array, $keyword_generic);
}
}
$switch = 0;
} else {
$switch = 1;
}
}
$set_what_generic = implode(', ', $generic_array);
$update_generic_query = "UPDATE memberinfo SET $set_what_generic WHERE user_id = $_SESSION[user_id]";
$dbc = mysqli_connect(DB_HOST, DB_USER, DB_PASSWORD, DB_NAME);
mysqli_query($dbc, $update_generic_query);
mysqli_close($dbc);
}
//===============WRONG ANSWER HANDLING=====================
}
//================GET QUESTION COUNT & SCORE QUIZ===========
//============ADJUST OVERALL TOTALS AND SUCCESS RATES===================
$update_score_query = "UPDATE memberinfo SET score = total_answers * overall_success_rate WHERE user_id = $_SESSION[user_id]";
$increase_totals_query = "UPDATE memberinfo SET total_quizzes_taken = total_quizzes_taken + 1, total_answers = total_answers + $question_count, total_correct = total_correct + $score WHERE user_id = $_SESSION[user_id]";
$adjust_success_query = "UPDATE memberinfo SET overall_success_rate = (total_correct / total_answers) * 100, phys_con_success = (phys_con_correct / phys_con_answers) * 100, abbr_success = (abbr_correct / abbr_answers) * 100, anatomy_success = (anatomy_correct / anatomy_answers) * 100, society_success = (society_correct / society_answers) * 100, career_success = (career_correct / career_answers) * 100, ment_heal_success = (ment_heal_correct / ment_heal_answers) * 100, tools_success = (tools_correct / tools_answers) * 100, other_success = (other_correct / other_answers) * 100, english_1_success = (english_1_correct / english_1_answers) * 100, english_2ot_success = (english_2ot_correct / english_2ot_answers) * 100, english_2pt_success = (english_2pt_correct / english_2pt_answers) * 100, english_2sw_success = (english_2sw_correct / english_2sw_answers) * 100 WHERE user_id = $_SESSION[user_id]";
$dbc = mysqli_connect(DB_HOST, DB_USER, DB_PASSWORD, DB_NAME);
mysqli_query($dbc, $increase_totals_query);
mysqli_query($dbc, $adjust_success_query);
mysqli_query($dbc, $update_score_query);
//===============UPDATE THE RANKING CHARTS====================
//==========FIRS FLUSH ALL RANKINGS TO 0===================
$flush_rankings = "UPDATE memberinfo SET rank = 0";
mysqli_query($dbc, $flush_rankings);
//==========FIRS FLUSH ALL RANKINGS TO 0===================
//==========NEXT GET ELIGIBLE MEMBERS====================
$get_eligible_scores = "SELECT user_id FROM memberinfo WHERE total_quizzes_taken > 0 AND overall_success_rate >= 40 ORDER BY score DESC, overall_success_rate DESC, total_correct DESC";
$eligible_data = mysqli_query($dbc, $get_eligible_scores);
//==========NEXT GET ELIGIBLE MEMBERS====================
//==========LOOP THROUGH AND UPDATE THE DATABASE=================
$rank_number = 1;
while ($member_data = mysqli_fetch_array($eligible_data)) {
$rank_update_query = "UPDATE memberinfo SET rank = $rank_number WHERE user_id = $member_data[user_id]";
mysqli_query($dbc, $rank_update_query);
$rank_number++;
}
//==========LOOP THROUGH AND UPDATE THE DATABASE=================
//===============UPDATE THE RANKING CHARTS====================
mysqli_close($dbc);
//============ADJUST OVERALL TOTALS AND SUCCESS RATES===================
//=================DISPLAY SCORE & APPROPRIATE MESSAGE=========
echo '<div class="quiz_results">';
echo '<div class="container">';
if ($score == 10) {
echo '<h2 class="center">Perfect Score!!!</h2>';
} else if ($score > 7 && $score < 10) {
echo '<h2 class="center">Well Done!</h2>';
} else if ($score > 5 && $score < 8) {
echo '<h2 class="center">Good!</h2>';
} else if ($score > 3 && $score < 6) {
echo '<h2 class="center">Try a little harder!</h2>';
} else if ($score > 1 && $score < 4) {
echo '<h2 class="center">Oooh. Not good.</h2>';
} else if ($score <= 1) {
echo '<h2 class="center">Seriously? That bad?</h2>';
} else {
echo '<h2 class="center">How\'d you even get this score??</h2>';
}
echo '<h1 class="center">You scored ' . $score . '/' . $question_count . '</h1>';
//=================DISPLAY SCORE & APPROPRIATE MESSAGE=========
//================COMPARE AND DISPLAY ANSWERS=================
?>
<div id="quiz_table_headings" class="row">
<h2 class="col-xs-6">Correct Answer</h2>
<h2 class="col-xs-6">Your Answer</h2>
</div>
<?php
for ($i = 0; $i < $question_count; $i++) {
echo '<div id="quiz_table_question" class="row">';
echo '<p id="quiz_table_question_inner" class="col-xs-12">Question ' . ($i + 1) . ': ' . $_SESSION['question_prompts'][$i] . '</p>';
echo '</div>';
echo '<div id="quiz_table_data" class="row">';
echo '<p id="quiz_table_answer" class="col-xs-6">' . $_SESSION['correct_answers'][$i] . '</p>';
if ($_POST[$i] == $_SESSION['correct_answers'][$i]) {
echo '<p id="quiz_table_correct" class="col-xs-6">' . $_POST[$i] . '</p>';
} else {
echo '<p id="quiz_table_wrong" class="col-xs-6">' . $_POST[$i] . '</p>';
}
echo '</div>';
echo '<hr>';
}
echo '</div>';
//================COMPARE AND DISPLAY ANSWERS=================
//===========CREATE END OF QUIZ LINKS=====================
$replay_url = 'startquiz.php?';
$args_array = [];
for ($i = 0; $i < count($current_quiz); $i++) {
$arg = 'quiz' . $i . '=' . $current_quiz[$i];
array_push($args_array, $arg);
}
$link_args = "";
$link_args = implode('&', $args_array);
$replay_url .= $link_args;
//=============DISPLAY THE BUTTONS=====================
echo '<div class="container">';
echo '<div id="quiz_finish_buttons_row" class="row">';
echo '<div id="quiz_finish_buttons_col" class="col-xs-6">';
echo '<a class="centered-button" href="' . $replay_url . '">Take This Quiz Again</a>';
echo '</div>';
echo '<div id="quiz_finish_buttons_col" class="col-xs-6">';
echo '<a class="centered-button" href="quizselect.php">Back to Quiz Select</a><br />';
echo '</div>';
echo '</div></div>';
echo '</div>';
//=============DISPLAY THE BUTTONS=====================
//===========CREATE END OF QUIZ LINKS=====================
require_once('bootstrapfooter.php');
?>
I apologize for posting the entire code for each page, but I'm not a professional programmer and I'm not sure what is relevant and what isn't.
The problem has been resolved. It turns out the issue was with the php.ini file on the hosting site. They recently made some changes that I was unaware of and the temporary storage location for session files/variables became undefined. Once I edited that information in the .ini file, everything worked just fine.

unable to display :active page in my pagination function

am using following function to display pagination
public function paginationLinks(){
$outputString = "";
$q = $this->db->query('SELECT COUNT(*) FROM videos');
$res = $q->fetch();
$newsNumber = $res[0];
$q->closeCursor();
for($i = 1; $i <= ceil($newsNumber / $this->newsByPage); $i++){
$outputString .="<li><a href='?page=" . $i . "'>" . $i . "</a></li> ";
}
return $outputString;
}
and this is how i display
<ul class="pagination pagination-sm">
<?php echo $news->paginationLinks(); ?>
</ul>
now bootstrap doesn't display active page its because of function
how do i add some more option like next, previous and :active
just replace your function with this one
public function paginationLinks(){
$outputString = "";
$crpage = isset($_GET['page']) && trim($_GET['page']) != ''?trim($_GET['page']):1;
$q = $this->db->query('SELECT COUNT(*) FROM videos');
$res = $q->fetch();
$newsNumber = $res[0];
$q->closeCursor();
for($i = 1; $i <= ceil($newsNumber / $this->newsByPage); $i++){
if($crpage == $i){
$outputString .="<li class='active'><a href='?page=" . $i . "'>" . $i . "</a></li> ";
}else{
$outputString .="<li><a href='?page=" . $i . "'>" . $i . "</a></li> ";
}
}
return $outputString;
}
For next or previous see that link
great example for PHP pagination.
Please try this .I hope this help you
public function paginationLinks(){
$num_rec_per_page = 10;
$outputString = "";
$page = (isset($_GET['page']) && $_GET['page'] != '') ? trim($_GET['page']) : 1;
$start_from = ($page-1) * $num_rec_per_page;
$q = $this->db->query('SELECT COUNT(*) FROM videos');
$res = $q->fetch();
$total_records = $res[0];
$q->closeCursor();
$total_pages = ceil($total_records / $num_rec_per_page);
$outputString .= "<li><a href='?page=1'>".'|<'."</a></li>"; // Goto 1st page
if($page > 1){
$prev = $page - 1;
$outputString .= "<li><a href='?page=".$prev."'>Prev</a></li>"; // Goto previous page
}
for ($i=1; $i<=$total_pages; $i++) {
$activeClass = ($page == $i) ? 'active' : '';
$outputString .="<li class=".$activeClass."><a href='?page=" . $i . "'>" . $i . "</a></li> ";
}
if($page < $total_pages){
$next = $page + 1;
$outputString .= "<li><a href='?page=".$next."'>Next</a></li>"; // Goto Next page
}
if($page > 1){
$outputString .= "<li><a href='?page=".$total_pages."'>".'|>'."</a></li>"; // Goto last page
}
return $outputString;
}

Custom table sorting not working correct

I am creating a data table that has sortable links but when I click on the link say "username" if i click on that multiple times it makes the url have lots of asc example: http://localhost/riwakawebsitedesigns-website/admin/users/status/ascascascascascascasc it should just be
Sorting Asc http://localhost/riwakawebsitedesigns-website/admin/users/status/asc
And then if click again and so on.
Sorting Desc http://localhost/riwakawebsitedesigns-website/admin/users/status/desc
This here is how pagination looks in url http://localhost/riwakawebsitedesigns-website/admin/users/1
I cannot figure out why each time i click on table head link that it creates so many asc etc. How can I fix it.
What's wrong with sort code. The pagination works fine. Please note I have use codeigniter pagination but not to my liking.
<?php
class Users extends MX_Controller {
public function index() {
$this->getList();
}
public function getList() {
$this->load->library('paginations');
$sort_segment = $this->uri->segment(3);
if (isset($sort_segment)) {
$sort = $sort_segment;
} else {
$sort = 'username';
}
$order_segment = $this->uri->segment(3);
if (isset($order_segment)) {
$order = $order_segment;
} else {
$order = 'asc';
}
$page_segment = $this->uri->segment(4);
if (isset($page_segment)) {
$page = $page_segment;
} else {
$page = 1;
}
$url = '';
if (isset($sort_segment)) {
$url .= $sort_segment;
}
if (isset($order_segment)) {
$url .= $order_segment;
}
if (isset($page_segment)) {
$url .= $page_segment;
}
$data['title'] = "Users";
$this->load->model('admin/user/model_user');
$admin_limit = "1";
$filter_data = array(
'sort' => $sort,
'order' => $order,
'start' => ($page - 1) * $admin_limit,
'limit' => $admin_limit
);
$user_total = $this->model_user->getTotalUsers();
$results = $this->model_user->getUsers($filter_data);
foreach ($results as $result) {
$data['users'][] = array(
'user_id' => $result['user_id'],
'username' => $result['username'],
'date_added' => $result['date_added'],
'edit' => site_url('admin/users/edit' .'/'. $result['user_id'])
);
}
$url = '';
if ($order == 'asc') {
$url .= 'desc';
} else {
$url .= 'asc';
}
if (isset($page_segment)) {
$url .= $page_segment;
}
$data['sort_username'] = site_url('admin/users' .'/'. 'username' .'/'. $url);
$data['sort_status'] = site_url('admin/users' .'/'. 'status' .'/'. $url);
$data['sort_date_added'] = site_url('admin/users' .'/'. 'date_added' .'/'. $url);
$url = '';
if (isset($sort_segment)) {
$url .= $sort_segment;
}
if (isset($order_segment)) {
$url .= $order_segment;
}
$paginations = new Paginations();
$paginations->total = $user_total;
$paginations->page = $page;
$paginations->limit = "1";
$paginations->url = site_url('admin/users' .'/'. $url .'/'. '{page}');
$data['pagination'] = $paginations->render();
$paginations_lang = "Showing %d to %d of %d (%d Pages)";
$data['results'] = sprintf($paginations_lang, ($user_total) ? (($page - 1) * $admin_limit) + 1 : 0, ((($page - 1) * $admin_limit) > ($user_total - $admin_limit)) ? $user_total : ((($page - 1) * $admin_limit) + $admin_limit), $user_total, ceil($user_total / $admin_limit));
$data['sort'] = $sort;
$data['order'] = $order;
$this->load->view('template/user/users_list.tpl', $data);
}
}
My Library
<?php
class Paginations {
public $total = 0;
public $page = 1;
public $limit = 20;
public $num_links = 8;
public $url = '';
public $text_first = '|<';
public $text_last = '>|';
public $text_next = '>';
public $text_prev = '<';
public function render() {
$total = $this->total;
if ($this->page < 1) {
$page = 1;
} else {
$page = $this->page;
}
if (!(int)$this->limit) {
$limit = 10;
} else {
$limit = $this->limit;
}
$num_links = $this->num_links;
$num_pages = ceil($total / $limit);
$this->url = str_replace('%7Bpage%7D', '{page}', $this->url);
$output = '<ul class="pagination">';
if ($page > 1) {
$output .= '<li>' . $this->text_first . '</li>';
$output .= '<li>' . $this->text_prev . '</li>';
}
if ($num_pages > 1) {
if ($num_pages <= $num_links) {
$start = 1;
$end = $num_pages;
} else {
$start = $page - floor($num_links / 2);
$end = $page + floor($num_links / 2);
if ($start < 1) {
$end += abs($start) + 1;
$start = 1;
}
if ($end > $num_pages) {
$start -= ($end - $num_pages);
$end = $num_pages;
}
}
for ($i = $start; $i <= $end; $i++) {
if ($page == $i) {
$output .= '<li class="active"><span>' . $i . '</span></li>';
} else {
$output .= '<li>' . $i . '</li>';
}
}
}
if ($page < $num_pages) {
$output .= '<li>' . $this->text_next . '</li>';
$output .= '<li>' . $this->text_last . '</li>';
}
$output .= '</ul>';
if ($num_pages > 1) {
return $output;
} else {
return '';
}
}
}
Thanks so much to #AdrienXL which gave me the idea what problem was.
I now have fixed it. I had doubled up on my page and sort and orders $_GET. So there for i have now just used uri segments and removed the doubled up code and change a couple of things in model
For people who do not want to use codeigniter pagination class.
You can use my example:
My Users:
<?php
class Users extends MX_Controller {
public function index() {
$this->load->library('paginations');
$this->load->model('admin/user/model_user');
// Sort
if (null !==($this->uri->segment(3))) {
$sort = $this->uri->segment(3);
} else {
$sort = 'username';
}
// Order
if (null !==($this->uri->segment(4))) {
$order = $this->uri->segment(4);
} else {
$order = 'asc';
}
// Page
if (null !==($this->uri->segment(3))) {
$page = $this->uri->segment(3);
} else {
$page = 1;
}
$url = '';
// Sort
if (null !==($this->uri->segment(3))) {
$url .= $this->uri->segment(3);
}
// Order
if (null !==($this->uri->segment(4))) {
$url .= $this->uri->segment(4);
}
// Page Number
if (null !==($this->uri->segment(3))) {
$url .= $this->uri->segment(3);
}
$admin_limit = "1";
$filter_data = array(
'sort' => $sort,
'order' => $order,
'start' => ($page - 1) * $admin_limit,
'limit' => $admin_limit
);
$user_total = $this->model_user->getTotalUsers();
$results = $this->model_user->getUsers($filter_data);
foreach ($results as $result) {
$data['users'][] = array(
'user_id' => $result['user_id'],
'username' => $result['username'],
'status' => ($result['status'] ? "Enabled" : "Disabled"),
'date_added' => date(strtotime($result['date_added'])),
'edit' => site_url('admin/users/edit' .'/'. $result['user_id'] . $url)
);
}
$url = '';
if ($order == 'asc') {
$url .= 'desc';
} else {
$url .= 'asc';
}
$data['sort_username'] = site_url('admin/users' .'/'. 'username' .'/'. $url);
$data['sort_status'] = site_url('admin/users' .'/'. 'status' .'/'. $url);
$data['sort_date_added'] = site_url('admin/users' .'/'. 'date_added' .'/'. $url);
$url = '';
$paginations = new Paginations();
$paginations->total = $user_total;
$paginations->page = $page;
$paginations->limit = $admin_limit;
$paginations->url = site_url('admin/users' .'/'. $url . '{page}');
$data['pagination'] = $paginations->render();
$paginations_lang = "Showing %d to %d of %d (%d Pages)";
$data['results'] = sprintf($paginations_lang, ($user_total) ? (($page - 1) * $admin_limit) + 1 : 0, ((($page - 1) * $admin_limit) > ($user_total - $admin_limit)) ? $user_total : ((($page - 1) * $admin_limit) + $admin_limit), $user_total, ceil($user_total / $admin_limit));
$data['sort'] = $sort;
$data['order'] = $order;
$this->load->view('template/user/users_list.tpl', $data);
}
}
My View
<div class="table-responsive">
<table class="table table-striped table-bordered table-hover">
<thead>
<tr>
<td class="text-left"><?php if ($sort == 'username') { ?>
Username
<?php } else { ?>
Username
<?php } ?></td>
<td class="text-left"><?php if ($sort == 'status') { ?>
Status
<?php } else { ?>
Status
<?php } ?></td>
<td class="text-left"><?php if ($sort == 'date_added') { ?>
Date Added
<?php } else { ?>
Date Added
<?php } ?></td>
<td class="text-right">Action</td>
</tr>
</thead>
<tbody>
<?php foreach ($users as $user) { ?>
<tr>
<td><?php echo $user['username'];?></td>
<td><?php echo $user['status'];?></td>
<td><?php echo $user['date_added'];?></td>
<td><a href="<?php echo $user['edit'];?>">Edit</td>
</tr>
<?php } ?>
</tbody>
</table>
<div class="row">
<div class="col-sm-6 text-left"><?php echo $pagination; ?></div>
<div class="col-sm-6 text-right"><?php echo $results; ?></div>
</div>
</div>
Model Function
public function getUsers($data = array()) {
$sql = "SELECT * FROM `" . $this->db->dbprefix . "user`";
$sort_data = array(
'username',
'status',
'date_added'
);
if (isset($data['sort']) && in_array($data['sort'], $sort_data)) {
$sql .= " ORDER BY " . $data['sort'];
} else {
$sql .= " ORDER BY username";
}
if (isset($data['order']) && ($data['order'] == 'desc')) {
$sql .= " desc";
} else {
$sql .= " asc";
}
if (isset($data['start']) || isset($data['limit'])) {
if ($data['start'] < 0) {
$data['start'] = 0;
}
if ($data['limit'] < 1) {
$data['limit'] = 20;
}
$sql .= " LIMIT " . (int)$data['start'] . "," . (int)$data['limit'];
}
$query = $this->db->query($sql);
return $query->result_array();
}
Routes:
$route['admin/users'] = "admin/user/users/index";
$route['admin/users/edit/(:any)'] = "admin/user/users/edit/$1";
$route['admin/users/(:any)'] = "admin/user/users/index/$1";
$route['admin/users/(:any)/(:any)/(:any)'] = "admin/user/users/index/$1/$2/$3";
Custom Library
<?php
class Paginations {
public $total = 0;
public $page = 1;
public $limit = 20;
public $num_links = 8;
public $url = '';
public $text_first = '|<';
public $text_last = '>|';
public $text_next = '>';
public $text_prev = '<';
public function render() {
$total = $this->total;
if ($this->page < 1) {
$page = 1;
} else {
$page = $this->page;
}
if (!(int)$this->limit) {
$limit = 10;
} else {
$limit = $this->limit;
}
$num_links = $this->num_links;
$num_pages = ceil($total / $limit);
$this->url = str_replace('%7Bpage%7D', '{page}', $this->url);
$output = '<ul class="pagination">';
if ($page > 1) {
$output .= '<li>' . $this->text_first . '</li>';
$output .= '<li>' . $this->text_prev . '</li>';
}
if ($num_pages > 1) {
if ($num_pages <= $num_links) {
$start = 1;
$end = $num_pages;
} else {
$start = $page - floor($num_links / 2);
$end = $page + floor($num_links / 2);
if ($start < 1) {
$end += abs($start) + 1;
$start = 1;
}
if ($end > $num_pages) {
$start -= ($end - $num_pages);
$end = $num_pages;
}
}
for ($i = $start; $i <= $end; $i++) {
if ($page == $i) {
$output .= '<li class="active"><span>' . $i . '</span></li>';
} else {
$output .= '<li>' . $i . '</li>';
}
}
}
if ($page < $num_pages) {
$output .= '<li>' . $this->text_next . '</li>';
$output .= '<li>' . $this->text_last . '</li>';
}
$output .= '</ul>';
if ($num_pages > 1) {
return $output;
} else {
return '';
}
}
}

Paging for directory listing in php

I'm trying to get the paging for directory listing script.
Here is the original code for the function.
This function list all the mp3 files in the directory and some file information.
$songs is holding the array infomation
original code
function htmlSongs(&$tmpl, $path_raw, $songs, $custom_pls = false, $c_pls_arr = null, $lofi = false, $various, $dir_write, $song_ratings) {
global $z_url_base, $z_self, $z_img_play, $z_img_lofi, $z_img_down,
$z_admin, $z_img_new, $z_img_edit, $z_self_raw, $zc, $z_db,$img_src;
$i = 0;
$check_boxes = false;
$diff = $zc['new_time']*60*60*24;
if (($z_admin && $zc['cache']) || ($zc['playlists'] && $zc['session_pls']) || $zc['play_sel'] || $zc['cmp_sel']) {
$check_boxes = true;
}
$tmpl = str_replace('{$songs_form_opts}', "name='songs' method='post' action='${z_self}p=$path_raw'", $tmpl);
$temp_section = tmpGetSect($tmpl, "SONGROW");
$html = "";
$rating = ($z_db && $zc['rating_files']);
foreach ($songs as $song => $opts) {
$temp_song = $temp_section;
$valign = ($opts['blurb']) ? "valign='top'" : "";
$song_raw = getURLencodedPath($song);
$song_title = formatSongTitle(basename($song));
$temp_song = str_replace('{$row}', $i, $temp_song);
$temp_song = str_replace('{$valign}', $valign, $temp_song);
$t_blurb = ($dir_write) ? "${opts['blurb']} <a href='${z_self_raw}&pl=".getURLencodedPath(basename($song))."&l=22&m=3'>$z_img_edit</a>" : $opts['blurb'];
$temp_song = str_replace('{$song_blurb}', $t_blurb, $temp_song);
$t_song_opts = "";
$remote = false;
if ($zc['fake'] && isset($opts['fake'])) {
$fi = ($zc['mp3_info']) ? "<td colspan='4'> </td>" : "";
$temp_song = tmpDelSec($temp_song,"SONGINFO", $fi);
$fi = ($rating) ? "<td colspan='2'> </td>" : "";
$temp_song = tmpDelSec($temp_song,"SONGVOTE", $fi);
$temp_song = tmpDelSec($temp_song,"SONGRATING");
$t_song_title = preg_replace("/\.(".$zc['fake_ext'].")$/i","",$song_title);
} else {
$url_play = $url_end = "";
if ($zc['mp3_info'] || $zc['mp3_id3']) {
if ($zc['remote'] && preg_match("/\.(".$zc['remote_ext'].")$/i", $song)) {
$mp3 = new remoteFile($zc['mp3_dir']."/$song", $zc['mp3_info'], $zc['mp3_id3']);
$remote = true;
} else {
$mp3 = new mp3($zc['mp3_dir']."/$song", $zc['mp3_info'], $zc['mp3_id3'], $zc['mp3_info_faster']);
}
}
if ($check_boxes) {
$checked = ($custom_pls && in_array($song, $c_pls_arr)) ? " checked='checked'" : "";
$t_song_opts .= "<input type='checkbox' name='mp3s[]' value='$song_raw'$checked /> ";
} else {
$t_song_opts .= " ";
}
if ($zc['download']) {
if ($remote) {
if (isset($mp3->download)) $t_song_opts .= "<a href='".$mp3->download."'>$z_img_down</a> ";
} else {
$surl = ($zc['stream_int']) ? "${z_self}l=12&p=$song_raw" : "$z_url_base/".getURLencodedPath2($song);
$t_song_opts .= "<a href='$surl&Oauth=$newssid'>$z_img_down</a> ";
}
}
if ($zc['play']) {
$url_play = "<a type=\"audio/mpeg\" title='$song_title' href='$mp3->url' >";
$url_end = "</a>";
if($mp3->url != ""){
$t_song_opts .= "$url_play </a> ";
}else{
$t_song_opts .= "";
}
}
if ($zc['low']) {
$tmp = " <a href='${z_self}l=8&p=";
if (isset($opts['lofi'])) {
$t_song_opts .= "$tmp".preg_replace("/\.(".$zc['ext_mus'].")$/i", $zc['low_suf'].".$1", $song_raw).
"&m=1'>$z_img_lofi</a> ";
} elseif($zc['resample'] && preg_match("/\.(".$zc['ext_enc'].")$/i", $song)) {
$t_song_opts .= "$tmp$song_raw&m=6'>$z_img_lofi</a> ";
}
}
if ($zc['new_highlight'] && isset($opts['mtime']) && ($now - $opts['mtime'] < $diff)) {
if ($zc['new_img']) {
$new_end = $z_img_new;
$new_beg = "";
} else {
$new_beg = $zc['new_beg'];
$new_end = $zc['new_end'];
}
} else {
$new_beg = $new_end = "";
}
$t_song_title = "$new_beg";
if ($zc['mp3_id3'] && $mp3->tag) {
if ($various && !empty($mp3->artist)) $t_song_title .= "$mp3->artist - ";
$t_song_title .= $mp3->title;
} else {
$subdir_images = "";
$t_song_title .= "$song_title";
}
$t_song_titles = "$new_beg";
if ($zc['mp3_id3'] && $mp3->tag) {
if ($various && !empty($mp3->artist)) $t_song_title .= "$mp3->artist - ";
$t_song_titles .= $mp3->title;
} else {
//$t_song_titles .= "<a href='$surl' type='audio/mpeg' title='$song_title'><img src='$img_src' style='display:none' /></a>";
$t_song_titles .= "";
}
$t_song_title .= "$new_end";
if ($zc['mp3_info']) {
if ($mp3->info == 1) {
$t_time = $mp3->time;
$t_bitrate = "$mp3->bitrate kbps";
$t_frequency = round($mp3->frequency/1000,1). " kHz";
$t_size = sprintf("%.2f", round($mp3->filesize/1000000,2))." Mb";
} else {
$t_size = (!$remote) ? sprintf("%.2f", round($mp3->filesize/1000000,2))." Mb" : " ";
$t_time = $t_bitrate = $t_frequency = " ";
}
$temp_song = str_replace('{$song_time}', $t_time, $temp_song);
$temp_song = str_replace('{$song_bitrate}', $t_bitrate, $temp_song);
$temp_song = str_replace('{$song_frequency}', $t_frequency, $temp_song);
$temp_song = str_replace('{$song_size}', $t_size, $temp_song);
} else {
$temp_song = tmpDelSec($temp_song,"SONGINFO");
}
if ($rating) {
$temp_song = str_replace('{$song_vote}', htmlVote($song), $temp_song);
$rating = (!empty($song_ratings) && isset($song_ratings[$song])) ? htmlVoteFormat($song_ratings[$song]) : " ";
$temp_song = str_replace('{$song_rating}', $rating, $temp_song);
} else {
$temp_song = tmpDelSec($temp_song,"SONGVOTE");
$temp_song = tmpDelSec($temp_song,"SONGRATING");
}
}
$temp_song = str_replace('{$song_title}', $t_song_title, $temp_song);
$temp_song = str_replace('{$song_titles}', $t_song_titles, $temp_song);
$temp_song = str_replace('{$song_opts}', $t_song_opts, $temp_song);
$temp_song = str_replace('{$pageshtml}', $t_pageshtml, $temp_song);
$html .= $temp_song;
$i = ++$i % 2;
}
$tmpl = tmpDelSec($tmpl,"SONGROW",$html);
$t_so_check = $t_so_sel = $t_so_pls = "";
if ($z_admin && $zc['cache']) {
$submit = ($custom_pls) ? _ZUPDATECUSTOM : _ZCREATECUSTOM;
$t_so_check .= "<input type='submit' value='$submit ' onClick=\"SubmitForm('songs','&l=3&z=3',false);\"/>";
}
if ($check_boxes) {
$t_so_check .= " "._ZCHECK.": "._ZALL." | ".
""._ZNONE."";
if ($zc['play_sel'] || $zc['cmp_sel']) {
$url_beg2 = " <a class='htrack' type='audio/mpeg' href=\"javascript:CheckIt('songs',";
$t_so_sel .= _ZSELECTED.": ";
$err = _ZERR_SEL;
if ($zc['play'] && $zc['play_sel']) { $t_so_sel .= "$url_beg2'${z_self}l=8&m=7',true,'$err');\">$z_img_play</a>"; }
if ($lofi) { $t_so_sel .= "$url_beg2'${z_self}l=8&m=7&lf=true',true,'$err');\">$z_img_lofi</a>"; }
if ($zc['download'] && $zc['cmp_sel']) { $t_so_sel .= "$url_beg2'&l=8&m=8',false,'$err');\">$z_img_down</a>"; }
}
}
$title = substr($path_raw,strrpos($path_raw,"/")+1);
$t_so_pls = ($zc['playlists']) ? htmlPlaylistFormElements('songs') : " ";
$tmpl = str_replace('{$row}',$i, $tmpl);
$tmpl = str_replace('{$so_check}',$t_so_check, $tmpl);
$tmpl = str_replace('{$so_select}',$t_so_sel, $tmpl);
$tmpl = str_replace('{$so_playlist}',$t_so_pls, $tmpl);
$tmpl = str_replace('{$movie_title}', $title, $tmpl);
Here is the some workaround to get the paging, this function is working but it's not showing the file information such as file name, time, size
This is the edited code.
function htmlSongs(&$tmpl, $path_raw, $songs, $custom_pls = false, $c_pls_arr = null, $lofi = false, $various, $dir_write, $song_ratings) {
global $z_url_base, $z_self, $z_img_play, $z_img_lofi, $z_img_down,
$z_admin, $z_img_new, $z_img_edit, $z_self_raw, $zc, $z_db,$img_src;
$i = 0;
$check_boxes = false;
$diff = $zc['new_time']*60*60*24;
if (($z_admin && $zc['cache']) || ($zc['playlists'] && $zc['session_pls']) || $zc['play_sel'] || $zc['cmp_sel']) {
$check_boxes = true;
}
$tmpl = str_replace('{$songs_form_opts}', "name='songs' method='post' action='${z_self}p=$path_raw'", $tmpl);
$temp_section = tmpGetSect($tmpl, "SONGROW");
$html = "";
$rating = ($z_db && $zc['rating_files']);
$i = $stat_prev = 0;
$p = 1;
$currents = htmlspecialchars($_GET['showpage']);
$pages = array_chunk($songs, 10);
$t_pageshtml .= '<center>Page '.($currents+1).' of '.count($pages).' <br>Pages: ';
for($i=1; $i< count($pages)+1; $i++){
$t_pageshtml .= ''.$i.' ';
}
$t_pageshtml .= '</center>';
$pgkey = (int)htmlspecialchars($_GET['showpage']);
$pages[$pgkey];
foreach ($pages[$pgkey] as $song => $opts) {
$temp_song = $temp_section;
$valign = ($opts['blurb']) ? "valign='top'" : "";
$song_raw = getURLencodedPath($song);
$song_title = formatSongTitle(basename($song));
$temp_song = str_replace('{$row}', $i, $temp_song);
$temp_song = str_replace('{$valign}', $valign, $temp_song);
$t_blurb = ($dir_write) ? "${opts['blurb']} <a href='${z_self_raw}&pl=".getURLencodedPath(basename($song))."&l=22&m=3'>$z_img_edit</a>" : $opts['blurb'];
$temp_song = str_replace('{$song_blurb}', $t_blurb, $temp_song);
$t_song_opts = "";
$remote = false;
if ($zc['fake'] && isset($opts['fake'])) {
$fi = ($zc['mp3_info']) ? "<td colspan='4'> </td>" : "";
$temp_song = tmpDelSec($temp_song,"SONGINFO", $fi);
$fi = ($rating) ? "<td colspan='2'> </td>" : "";
$temp_song = tmpDelSec($temp_song,"SONGVOTE", $fi);
$temp_song = tmpDelSec($temp_song,"SONGRATING");
$t_song_title = preg_replace("/\.(".$zc['fake_ext'].")$/i","",$song_title);
} else {
$url_play = $url_end = "";
if ($zc['mp3_info'] || $zc['mp3_id3']) {
if ($zc['remote'] && preg_match("/\.(".$zc['remote_ext'].")$/i", $song)) {
$mp3 = new remoteFile($zc['mp3_dir']."/$song", $zc['mp3_info'], $zc['mp3_id3']);
$remote = true;
} else {
$mp3 = new mp3($zc['mp3_dir']."/$song", $zc['mp3_info'], $zc['mp3_id3'], $zc['mp3_info_faster']);
}
}
if ($check_boxes) {
$checked = ($custom_pls && in_array($song, $c_pls_arr)) ? " checked='checked'" : "";
$t_song_opts .= "<input type='checkbox' name='mp3s[]' value='$song_raw'$checked /> ";
} else {
$t_song_opts .= " ";
}
if ($zc['download']) {
if ($remote) {
if (isset($mp3->download)) $t_song_opts .= "<a href='".$mp3->download."'>$z_img_down</a> ";
} else {
$surl = ($zc['stream_int']) ? "${z_self}l=12&p=$song_raw" : "$z_url_base/".getURLencodedPath2($song);
$t_song_opts .= "<a href='$surl&Oauth=$newssid'>$z_img_down</a> ";
}
}
if ($zc['play']) {
$url_play = "<a type=\"audio/mpeg\" title='$song_title' href='$mp3->url' >";
$url_end = "</a>";
if($mp3->url != ""){
$t_song_opts .= "$url_play </a> ";
}else{
$t_song_opts .= "";
}
}
if ($zc['low']) {
$tmp = " <a href='${z_self}l=8&p=";
if (isset($opts['lofi'])) {
$t_song_opts .= "$tmp".preg_replace("/\.(".$zc['ext_mus'].")$/i", $zc['low_suf'].".$1", $song_raw).
"&m=1'>$z_img_lofi</a> ";
} elseif($zc['resample'] && preg_match("/\.(".$zc['ext_enc'].")$/i", $song)) {
$t_song_opts .= "$tmp$song_raw&m=6'>$z_img_lofi</a> ";
}
}
if ($zc['new_highlight'] && isset($opts['mtime']) && ($now - $opts['mtime'] < $diff)) {
if ($zc['new_img']) {
$new_end = $z_img_new;
$new_beg = "";
} else {
$new_beg = $zc['new_beg'];
$new_end = $zc['new_end'];
}
} else {
$new_beg = $new_end = "";
}
$t_song_title = "$new_beg";
if ($zc['mp3_id3'] && $mp3->tag) {
if ($various && !empty($mp3->artist)) $t_song_title .= "$mp3->artist - ";
$t_song_title .= $mp3->title;
} else {
$subdir_images = "";
$t_song_title .= "$song_title";
}
$t_song_titles = "$new_beg";
if ($zc['mp3_id3'] && $mp3->tag) {
if ($various && !empty($mp3->artist)) $t_song_title .= "$mp3->artist - ";
$t_song_titles .= $mp3->title;
} else {
//$t_song_titles .= "<a href='$surl' type='audio/mpeg' title='$song_title'><img src='$img_src' style='display:none' /></a>";
$t_song_titles .= "";
}
$t_song_title .= "$new_end";
if ($zc['mp3_info']) {
if ($mp3->info == 1) {
$t_time = $mp3->time;
$t_bitrate = "$mp3->bitrate kbps";
$t_frequency = round($mp3->frequency/1000,1). " kHz";
$t_size = sprintf("%.2f", round($mp3->filesize/1000000,2))." Mb";
} else {
$t_size = (!$remote) ? sprintf("%.2f", round($mp3->filesize/1000000,2))." Mb" : " ";
$t_time = $t_bitrate = $t_frequency = " ";
}
$temp_song = str_replace('{$song_time}', $t_time, $temp_song);
$temp_song = str_replace('{$song_bitrate}', $t_bitrate, $temp_song);
$temp_song = str_replace('{$song_frequency}', $t_frequency, $temp_song);
$temp_song = str_replace('{$song_size}', $t_size, $temp_song);
} else {
$temp_song = tmpDelSec($temp_song,"SONGINFO");
}
if ($rating) {
$temp_song = str_replace('{$song_vote}', htmlVote($song), $temp_song);
$rating = (!empty($song_ratings) && isset($song_ratings[$song])) ? htmlVoteFormat($song_ratings[$song]) : " ";
$temp_song = str_replace('{$song_rating}', $rating, $temp_song);
} else {
$temp_song = tmpDelSec($temp_song,"SONGVOTE");
$temp_song = tmpDelSec($temp_song,"SONGRATING");
}
}
$temp_song = str_replace('{$song_title}', $t_song_title, $temp_song);
$temp_song = str_replace('{$song_titles}', $t_song_titles, $temp_song);
$temp_song = str_replace('{$song_opts}', $t_song_opts, $temp_song);
$temp_song = str_replace('{$pageshtml}', $t_pageshtml, $temp_song);
$html .= $temp_song;
$i = ++$i % 2;
$p++;
}
$tmpl = tmpDelSec($tmpl,"SONGROW",$html);
//$t_pageshtml = 'UUUU';
$t_so_check = $t_so_sel = $t_so_pls = "";
if ($z_admin && $zc['cache']) {
$submit = ($custom_pls) ? _ZUPDATECUSTOM : _ZCREATECUSTOM;
$t_so_check .= "<input type='submit' value='$submit ' onClick=\"SubmitForm('songs','&l=3&z=3',false);\"/>";
}
if ($check_boxes) {
$t_so_check .= " "._ZCHECK.": "._ZALL." | ".
""._ZNONE."";
if ($zc['play_sel'] || $zc['cmp_sel']) {
$url_beg2 = " <a class='htrack' type='audio/mpeg' href=\"javascript:CheckIt('songs',";
$t_so_sel .= _ZSELECTED.": ";
$err = _ZERR_SEL;
if ($zc['play'] && $zc['play_sel']) { $t_so_sel .= "$url_beg2'${z_self}l=8&m=7',true,'$err');\">$z_img_play</a>"; }
if ($lofi) { $t_so_sel .= "$url_beg2'${z_self}l=8&m=7&lf=true',true,'$err');\">$z_img_lofi</a>"; }
if ($zc['download'] && $zc['cmp_sel']) { $t_so_sel .= "$url_beg2'&l=8&m=8',false,'$err');\">$z_img_down</a>"; }
}
}
$title = substr($path_raw,strrpos($path_raw,"/")+1);
$t_so_pls = ($zc['playlists']) ? htmlPlaylistFormElements('songs') : " ";
$tmpl = str_replace('{$row}',$i, $tmpl);
$tmpl = str_replace('{$so_check}',$t_so_check, $tmpl);
$tmpl = str_replace('{$so_select}',$t_so_sel, $tmpl);
$tmpl = str_replace('{$so_playlist}',$t_so_pls, $tmpl);
$tmpl = str_replace('{$movie_title}', $title, $tmpl);
$tmpl = str_replace('{$pages_html}', $t_pageshtml, $tmpl);
}
This is the code for paging
$i = $stat_prev = 0;
$p = 1;
$currents = htmlspecialchars($_GET['showpage']);
$pages = array_chunk($songs, 10);
$t_pageshtml .= '<center>Page '.($currents+1).' of '.count($pages).' <br>Pages: ';
for($i=1; $i< count($pages)+1; $i++){
$t_pageshtml .= ''.$i.' ';
}
$t_pageshtml .= '</center>';
$pgkey = (int)htmlspecialchars($_GET['showpage']);
$pages[$pgkey];
i think something wrong here
original code
foreach ($songs as $song => $opts)
edited code
foreach ($pages[$pgkey] as $song => $opts) {
OK
I solved the problem my self.
here is the solution
i use array_slice
$i = $stat_prev = 0;
$p = 1;
$currents = htmlspecialchars($_GET['showpage']);
$pages = array_chunk($songs, 10);
$t_pageshtml .= '<center>Page '.($currents+1).' of '.count($pages).' <br>Pages: ';
for($i=1; $i< count($pages)+1; $i++){
$t_pageshtml .= ''.$i.' ';
}
$t_pageshtml .= '</center>';
$pgkey = (int)htmlspecialchars($_GET['showpage']);
$songs = array_slice($songs, $pgkey."0",10);
foreach ($songs as $song => $opts ) {
You can "paginate" any one-dimensional array by using the array_chunk function:
$pages = array_chunk($songs, $perPage = 10);
$pageCount = count($pages);
$currentPageSongs = $pages[$page-1]; # pages are zero-based

Categories