I'm trying to get search results to paginate if there are greater than 10 items found in the database. For some reason, even though the code recognises there are more than 10 items and creates links for subsequent pages, all search results are listed on the first page only. Anyone able to help please? Code is below:
for($i = 0; $i < $terms_count; $i++)
{
$search_terms_array[$i] = trim($search_terms_array[$i]);
${"query".$i} = $this->mysqli_link->query("SELECT prod_id, prod_tags FROM table WHERE prod_tags LIKE '%" . $search_terms_array[$i] . "%'");
if(${"query".$i}->num_rows < 1)
{
$zerocount++;
}
else
{
$rows = array();
while($row = ${"query".$i}->fetch_array())
{
$rows[] = $row;
}
foreach($rows as $row)
{
$search_id_results[] = $row['prod_id'];
}
}
}
if($zerocount == $terms_count)
{
echo $this->err_handle->fetch_error_text("search_terms_0_results");
return;
}
else
{
$search_results = array_values(array_unique($search_id_results));
$search_results_count = count($search_results);
$search_page_count = ceil($search_results_count / 10);
$search_page_first_result = ($search_page - 1) * 10;
echo '<p>Go to page: ';
for($i = 1; $i <= $search_page_count; $i++)
{
if($i == $search_page)
{
echo " <strong>" . $i . "</strong>";
}
else
{
echo ' ' . $i . '';
}
}
echo '</p><p> </p><p> </p>';
for($i = 0; $i < $search_results_count; $i++)
{
$query = $this->mysqli_link->query("SELECT * FROM table WHERE prod_id='" . $search_results[$i] . "' LIMIT " . $search_page_first_result . ", 10");
while($row = $query->fetch_array())
{
echo "<h4>" . $row['prod_name'] . "</h4><p><img src=\"includes/images/product_images/" . $row['prod_category'] . "/" . $row['prod_pic_filename'] . "\" alt=\"\" width=\"150\" height=\"200\" /></p><p>Price: £" . $row['prod_price'] . "</p><p>" . $row['prod_code'] . "</p><input type=\"number\" name=\"prod_qty\" maxlength=\"2\" /><input type=\"submit\" name=\"add_to_basket\" value=\"Add To Basket\" /></form></p><p> </p><p> </p>";
}
}
echo '<p>Go to page: ';
for($i = 1; $i <= $search_page_count; $i++)
{
if($i == $search_page)
{
echo " <strong>" . $i . "</strong>";
}
else
{
echo ' ' . $i . '';
}
}
echo '</p><p> </p><p> </p>';
}
Ok so I found a solution to this problem and the full function is now as follows:
public function product_search($search_terms, $search_page, $search_flag_check)
{
if($search_flag_check == "invalid")
{
echo $this->err_handle->fetch_error_text("invalid_ns_term");
return;
}
if($search_terms == "")
{
echo $this->err_handle->fetch_error_text("no_search_string");
return;
}
$search_terms = htmlspecialchars($search_terms);
$search_terms = $this->mysqli_link->real_escape_string(filter_var($search_terms, FILTER_SANITIZE_FULL_SPECIAL_CHARS, FILTER_FLAG_NO_ENCODE_QUOTES));
$search_terms_array = explode(" ", $search_terms);
$terms_count = count($search_terms_array);
$zerocount = 0;
$search_id_results = array();
for($i = 0; $i < $terms_count; $i++)
{
$search_terms_array[$i] = trim($search_terms_array[$i]);
${"query".$i} = $this->mysqli_link->query("SELECT prod_id, prod_tags FROM table WHERE prod_tags LIKE '%" . $search_terms_array[$i] . "%'");
if(${"query".$i}->num_rows < 1)
{
$zerocount++;
}
else
{
$rows = array();
while($row = ${"query".$i}->fetch_array())
{
$rows[] = $row;
}
foreach($rows as $row)
{
$search_id_results[] = $row['prod_id'];
}
}
}
if($zerocount == $terms_count)
{
echo $this->err_handle->fetch_error_text("search_terms_0_results");
return;
}
else
{
$search_results = array_values(array_unique($search_id_results));
$search_results_count = count($search_results);
$search_page_count = ceil($search_results_count / 10);
$search_page_first_result = ($search_page - 1) * 10;
$search_page_results_limit = 10;
if($search_page_first_result < 1)
{
$search_page_first_result = 1;
}
echo '<p>Go to page: ';
for($i = 1; $i <= $search_page_count; $i++)
{
if($i == $search_page)
{
echo " <strong>" . $i . "</strong>";
}
else
{
echo ' ' . $i . '';
}
}
echo '</p><p> </p><p> </p>';
$search_page_upper_limit = $search_page_first_result + 9;
if(array_key_exists($search_page_upper_limit, $search_results))
{
$search_results_limit = $search_page_first_result + $search_page_results_limit;
}
else
{
end($search_results);
$search_results_limit = key($search_results);
reset($search_results);
}
for($i = $search_page_first_result; $i <= $search_results_limit; $i++)
{
$query2 = $this->mysqli_link->query("SELECT * FROM table WHERE prod_id='" . $search_results[$i] . "'");
$row = $query2->fetch_array();
echo "<h4>" . $row['prod_name'] . "</h4><p><img src=\"includes/images/product_images/" . $row['prod_category'] . "/" . $row['prod_pic_filename'] . "\" alt=\"\" width=\"150\" height=\"200\" /></p><p>Price: £" . $row['prod_price'] . "</p><p>" . $row['prod_code'] . "</p><input type=\"number\" name=\"prod_qty\" maxlength=\"2\" /><input type=\"submit\" name=\"add_to_basket\" value=\"Add To Basket\" /></form></p><p> </p><p> </p>";
}
echo '<p>Go to page: ';
for($i = 1; $i <= $search_page_count; $i++)
{
if($i == $search_page)
{
echo " <strong>" . $i . "</strong>";
}
else
{
echo ' ' . $i . '';
}
}
echo '</p><p> </p><p> </p>';
}
}
It took a bit of thinking and I was about to give up, but then I thought about using the array keys to calculate the limits for each search page and after a bit of googling on relevant PHP array functions it all fell into place quite well.
I understand the code may not be very tidy right now and there may be ways to optimize/improve it, however for the time being it does the job.
Related
I have a csv file with some data inside.
When User type something in the search bar,it will return the relate data but these results are too much, I want to make a pagination.I don't have any idea, google a lot but can't find a way to do. Please help.
$filename = "Database.csv";
$delimiter = ",";
if (!file_exists($filename) || !is_readable($filename))
return false;
if ($delimiter == ',') {
$csv = array_map('str_getcsv', file($filename));
} else {
$lines = file($filename);
$line_num = count($lines);
$dm = [];
$csv = array_map('str_getcsv', $lines, array_pad($dm, $line_num, $delimiter));
}
array_walk($csv, function (&$row) use ($csv) {
$row = array_combine($csv[0], $row);
});
array_shift($csv);
$total_row_of_csv = count($csv);
$total_row = 0;
for ($i = 0; $i < $total_row_of_csv; $i++) {
if (preg_match("/$value/i", $csv[$i]['Catagory'])) {
echo "<tr>";
echo "<td>" . $csv[$i]['Ref'] . "</td>";
echo "<td>" . $csv[$i]['Catagory'] . "</td>";
echo "<td>" . $csv[$i]['JobTitle'] . "</td>";
echo "<td>" . $csv[$i]['Description'] . "</td>";
echo "<td>" . $csv[$i]['Salary'] . "</td>";
echo "<td>" . $csv[$i]['Nature'] . "</td>";
echo "</tr>";
$total_row++;
}
}
GET : index.php?page=2&search=purchasing
clear the page=1 for a new search
This function is done with get method not post, you can do it as the post by doing appropriately
<?php
// you can make this as post as you want
// i have made this as a get param function
$value = !empty($_GET['search']) ? $_GET['search'] : '';
$filename = "Database.csv";
$delimiter = ",";
if (!file_exists($filename) || !is_readable($filename))
return false;
if ($delimiter == ',') {
$csv = array_map('str_getcsv', file($filename));
} else {
$lines = file($filename);
$line_num = count($lines);
$dm = [];
$csv = array_map('str_getcsv', $lines, array_pad($dm, $line_num, $delimiter));
}
array_walk($csv, function (&$row) use ($csv) {
$row = array_combine($csv[0], $row);
});
array_shift($csv);
$total_row_of_csv = count($csv);
$countForPage = 0;
for ($i = 0; $i < $total_row_of_csv; $i++) {
//var_dump($csv[$i]['Catagory']);die();
// didint get the $value so commented id
if (preg_match("/$value/i", $csv[$i]['Catagory'])) {
$countForPage ++;
}
}
$countForPage;
$numPerPage = 10;
$numCurrPage = !empty($_GET['page']) ? $_GET['page'] : 1;
$numFromCnt = $numPerPage * ($numCurrPage - 1);
$numLastCnt = $numFromCnt + $numPerPage ;
$total_row = 0;
echo "<table>";
for ($i = 0; $i < $total_row_of_csv; $i++) {
//var_dump($csv[$i]['Catagory']);die();
// didint get the $value so commented id
if (preg_match("/$value/i", $csv[$i]['Catagory'])) {
//echo $total_row .">=". $numFromCnt ."&&". $total_row ."<". $numLastCnt; //die();
if($total_row >= $numFromCnt && $total_row < $numLastCnt) {
echo "<tr>";
echo "<td>" . $csv[$i]['Ref'] . "</td>";
echo "<td>" . $csv[$i]['Catagory'] . "</td>";
echo "<td>" . $csv[$i]['JobTitle'] . "</td>";
echo "<td>" . $csv[$i]['Description'] . "</td>";
echo "<td>" . $csv[$i]['Salary'] . "</td>";
echo "<td>" . $csv[$i]['Nature'] . "</td>";
echo "</tr>";
}
$total_row++;
}
}
//echo $total_row;die();
echo "</table>";
$links = generateLinks($countForPage, $numCurrPage, $numPerPage, $value);
echo $links;
function generateLinks($total_row_of_csv, $numCurrPage, $numPerPage, $search){
$pagLink = '';
if($numCurrPage > 1) {
$pagLink .= "<li class='active'><a href='csv_pagination.php?page="
.($numCurrPage-1)."&search=".$search."'>Prev</a></li>";
}
// for ($i=1; $i<=$total_row_of_csv; $i++) {
// if ($i==$numCurrPage) {
// $pagLink .= "<li class='active'><a href='csv_pagination.php?page="
// .$i."'>".$i."</a></li>";
// } else {
// $pagLink .= "<li><a href='csv_pagination.php?page=".$i."'>
// ".$i."</a></li>";
// }
// }
if($numCurrPage < ($total_row_of_csv/$numPerPage)) {
$pagLink .= "<li class='active'><a href='csv_pagination.php?page="
.($numCurrPage+1)."&search=".$search."'>Next</a></li>";
}
return $pagLink;
}
?>
I have a 'map' kind of thing for something im working on. Im drawing each tile out and then checking against a database to see if somebody is located at that tile.
The code works but only for the first result in the db.
Can anyone help. many thanks.
$sqlw = "SELECT id, player_coord_x, player_coord_y FROM player_game WHERE world_id='$world'";
$world_result = $player_stat->query($sqlw);
?>
<div class='map-grid'>
<?
$id = '';
$size = 16;
for($i = 1; $i <= $size; $i++) {
echo "<div class='map-grid-row'>";
for ($j=1; $j <= $size; $j++) {
// check for player at location
if ($world_result->num_rows > 0) {
while($w_row = $world_result->fetch_assoc()) {
$player_coord_x = $w_row['player_coord_x'];
$player_coord_y = $w_row['player_coord_y'];
$id = $w_row['id'];
}
}
if ($player_coord_x == $i and $player_coord_y == $j){
echo "<div class='map-grid-cell high'>";
echo "XXX";
echo "</div>";
}else{
echo "<div class='map-grid-cell high'>";
echo "<span class=\"map-small\">(x-$i y-$j)</span>";
echo "</div>";
}
}
echo "</div>";
}
?>
</div>
$sqlw = "SELECT id, player_coord_x, player_coord_y FROM player_game WHERE world_id='$world'";
$world_result = $player_stat->query($sqlw);
if($world_result->num_rows > 0){
while($w_row = $world_result->fetch_assoc()){
//first type of array
$player[] = array(
'x' => $w_row['player_coord_x'], //your player X record
'y' => $w_row['player_coord_y'], //your player Y record
'id' => $w_row['id'] //your player id
);
//second type of array
// OR store player's X and Y as key of array
$player[$w_row['player_coord_x'] . '-' . $w_row['player_coord_y']] = $w_row['id'];
// This are only if the player record will never repeat
}
}
?>
<div class="map-grid">
<?php
$size = 16;
for($i = 1; $i <= $size; $i++){
echo '<div class="map-grid-row">';
for($j = 1; $j <= $size; $j++){
//with first type of array
$exists = false;
foreach($player as $play){
if($play['x'] == $i && $play['y'] == $j){
$exists = true;
break; // break the loop once you got the result.
}
}
if($exists){ //Player exists? if no detect in foreach loop above, default exists would return false.
echo '<div class="map-grid-cell high">';
echo 'XXX';
echo '</div>';
} else {
echo '<div class="map-grid-cell high">';
echo '<span class="map-small">(x-' . $i . ' y-' . $j . ')</span>';
echo '</div>';
}
//second type of array
//Check if the key exists and if it's empty.
if(isset($player[$i.'-'.$j]) && !empty($player[$i.'-'.$j])){
echo '<div class="map-grid-cell high">';
echo 'XXX';
echo '</div>';
} else {
echo '<div class="map-grid-cell high">';
echo '<span class="map-small">(x-' . $i . ' y-' . $j . ')</span>';
echo '</div>';
}
}
}
?>
</div>
Hello I've got the following function:
function getProductInformation($productArr, $productNumber){
for ($i=0; $i < count($productArr[0]); $i++) {
$products[] = $productArr[0][$i];
}
for ($i=0; $i < count($productArr[1]); $i++) {
$sizes[] = $productArr[1][$i];
}
for ($i=0; $i < count($productArr[2]); $i++) {
$prices[] = $productArr[2][$i];
}
?><p><?php
return $products[$productNumber] . " " . $sizes[$productNumber] . " " . $prices[$productNumber];
?></p><?php
}
If i echo the function with an array and a number as params it will return the following:
<p>product size price</p>
Instead of the function only returning one paragraph i would like the result to look like this
<p>product</p> <p>size</p> <p>price</p>
All help appreciated!
Include HTML tags in strings:
function getProductInformation($productArr, $productNumber){
$products = array_values($productArr[0]);
$sizes = array_values($productArr[1]);
$prices = array_values($productArr[2]);
return "<p>" . $products[$productNumber] . "</p> <p>" . $sizes[$productNumber] . "</p> <p>" . $prices[$productNumber] . "</p>";
}
I have a follow up question on something I got help with here the other day (No Table Three Column Category Layout).
The script is as follows:
$res = mysql_query($query);
$system->check_mysql($res, $query, __LINE__, __FILE__);
$parent_node = mysql_fetch_assoc($res);
$id = (isset($parent_node['cat_id'])) ? $parent_node['cat_id'] : $id;
$catalist = '';
if ($parent_node['left_id'] != 1)
{
$children = $catscontrol->get_children_list($parent_node['left_id'], $parent_node['right_id']);
$childarray = array($id);
foreach ($children as $k => $v)
{
$childarray[] = $v['cat_id'];
}
$catalist = '(';
$catalist .= implode(',', $childarray);
$catalist .= ')';
$all_items = false;
}
$NOW = time();
/*
specified category number
look into table - and if we don't have such category - redirect to full list
*/
$query = "SELECT * FROM " . $DBPrefix . "categories WHERE cat_id = " . $id;
$result = mysql_query($query);
$system->check_mysql($result, $query, __LINE__, __FILE__);
$category = mysql_fetch_assoc($result);
if (mysql_num_rows($result) == 0)
{
// redirect to global categories list
header ('location: browse.php?id=0');
exit;
}
else
{
// Retrieve the translated category name
$par_id = $category['parent_id'];
$TPL_categories_string = '';
$crumbs = $catscontrol->get_bread_crumbs($category['left_id'], $category['right_id']);
for ($i = 0; $i < count($crumbs); $i++)
{
if ($crumbs[$i]['cat_id'] > 0)
{
if ($i > 0)
{
$TPL_categories_string .= ' > ';
}
$TPL_categories_string .= '' . $category_names[$crumbs[$i]['cat_id']] . '';
}
}
// get list of subcategories of this category
$subcat_count = 0;
$query = "SELECT * FROM " . $DBPrefix . "categories WHERE parent_id = " . $id . " ORDER BY cat_name";
$result = mysql_query($query);
$system->check_mysql($result, $query, __LINE__, __FILE__);
$need_to_continue = 1;
$cycle = 1;
$column = 1;
$TPL_main_value = '';
while ($row = mysql_fetch_array($result))
{
++$subcat_count;
if ($cycle == 1)
{
$TPL_main_value .= '<div class="col'.$column.'"><ul>' . "\n";
}
$sub_counter = $row['sub_counter'];
$cat_counter = $row['counter'];
if ($sub_counter != 0)
{
$count_string = ' (' . $sub_counter . ')';
}
else
{
if ($cat_counter != 0)
{
$count_string = ' (' . $cat_counter . ')';
}
else
{
$count_string = '';
}
}
if ($row['cat_colour'] != '')
{
$BG = 'bgcolor=' . $row['cat_colour'];
}
else
{
$BG = '';
}
// Retrieve the translated category name
$row['cat_name'] = $category_names[$row['cat_id']];
$catimage = (!empty($row['cat_image'])) ? '<img src="' . $row['cat_image'] . '" border=0>' : '';
$TPL_main_value .= "\t" . '<li>' . $catimage . '' . $row['cat_name'] . $count_string . '</li>' . "\n";
++$cycle;
if ($cycle == 7) // <---- here
{
$cycle = 1;
$TPL_main_value .= '</ul></div>' . "\n";
++$column;
}
}
if ($cycle >= 2 && $cycle <= 6) // <---- here minus 1
{
while ($cycle < 7) // <---- and here
{
$TPL_main_value .= ' <p> </p>' . "\n";
++$cycle;
}
$TPL_main_value .= '</ul></div>'.$number.'
' . "\n";
}
I was needing to divide the resulting links into three columns to fit my html layout.
We accomplished this by changing the numbers in the code marked with "// <---- here".
Because the amount of links returned could be different each time, I am trying to figure out how to change those numbers on the fly. I tried using
$number_a = mysql_num_rows($result);
$number_b = $number_a / 3;
$number_b = ceil($number_b);
$number_c = $number_b - 1;
and then replacing the numbers with $number_b or $number_c but that doesn't work. Any ideas?
As mentioned before, you can use the mod (%) function to do that.
Basically what it does is to get the remainder after division. So, if you say 11 % 3, you will get 2 since that is the remainder after division. You can then make use of this to check when a number is divisible by 3 (the remainder will be zero), and insert an end </div> in your code.
Here is a simplified example on how to use it to insert a newline after every 3 columns:
$cycle = 1;
$arr = range (1, 20);
$len = sizeof ($arr);
for ( ; $cycle <= $len; $cycle++)
{
echo "{$arr[$cycle - 1]} ";
if ($cycle % 3 == 0)
{
echo "\n";
}
}
echo "\n\n";
I'm making a calender planner with php/css/javascript/html.
I am trying to set each day of the month a class which is "day". I tried using the following:
**PHP CODE**
error_reporting(E_ALL);
ini_set('display_errors', '1');
include "scripts/connect_to_mysql.php";
$jobNameValue ='';
$monthDays = '';
$monthname = '';
$days = '';
//getting values for job names
$sql_job_name = mysql_query("SELECT * FROM jobs");
$num_job_name = mysql_num_rows($sql_job_name);
if($num_job_name >0) {
while ($row = mysql_fetch_array($sql_job_name)) {
$job_name = $row["job_name"];
$job_short_name = $row["job_short_name"];
$jobNameValue .= '<option value="' . $job_short_name . '">' . $job_name . '</option>';
}
} else {
$jobNameValue .= '<option value="NULL">No job listed</option>';
}
//getting values for months days
$sql_month_days = mysql_query("SELECT * FROM months");
$num_month_days = mysql_num_rows($sql_month_days);
if($sql_month_days > 0) {
while($row = mysql_fetch_array($sql_month_days)) {
$month_id = $row["id"];
$name = $row["name"];
$num_days = $row["num_days"];if($num_days === "31") {
for($i=1; $i <=31; $i++) {
$days .= '<span class="day">' . $i . '</span>';
}
} else {
if($num_days === "30") {
for($i=1; $i <=30; $i++) {
$days .= '<span class="day">' . $i . '</span>';
}
} else {
if($num_days === "29") {
for($i=1; $i <=29; $i++) {
$days .= '<span class="day">' . $i . '</span>';
}
}
}
}
$monthDays .= '<div id="monthContainer">
<span class="monthName">'. $name .'</span>
<div class="monthDaysContainter">
'. $days.'
</div>
</div>';
}
}
**HTML CODE**
<div id="container">
<div ="newJob">
<form action="<?php $_SERVER['PHP_SELF'] ?>" id="newJobForm">
<label for="jobName">Job Name:</label>
<select id="jobName">
<?php echo $jobNameValue; ?>
</select>
<input type="date">
<input type="submit" id="submit">
</form>
</div>
<div id="calander">
<?php echo $monthDays; ?>
</div>
</div>
It does not work correctly, it kept duplicating every month and I am not sure how to correctly right the php to achieve what was intended.
I am only a beginner at php so I am not good at the moment
Could anyone help me with this?
If there any more information you need, please don't hesitate to ask.
Thank you in advance!
Chris
Try just doing this and seeing if that fixes it, you don't need all of those if statements
for($i=1; $i <= $num_days; $i++) {
$days .= '<span class="day">' . $i . '</span>';
}
do not use ===,use ==,maybe your $num_days is integer
Your problem is that you are creating the whole thing in the while loop, so the days that are appended from the last call are also appended to the next output.
$tmpArray = array();
if($sql_month_days > 0) {
while($row = mysql_fetch_array($sql_month_days)) {
array_push($tmpArray, $row);
}
}
foreach($tmpArray as $k){
$monthDays .= '<div id="monthContainer"><span class="monthName">'. $k['name'] .'</span><div class="monthDaysContainter">'. calNumDays($k['num_days']).'</div></div>';
}
Update
Should you wish to keep what you already have
if($num_days === "31") {
$days = '';
for($i=1; $i <=31; $i++) {
$days .= '<span class="day">' . $i . '</span>';
}
} else {
if($num_days === "30") {
$days = '';
for($i=1; $i <=30; $i++) {
$days .= '<span class="day">' . $i . '</span>';
}
} else {
if($num_days === "29") {
$days = '';
for($i=1; $i <=29; $i++) {
$days .= '<span class="day">' . $i . '</span>';
}
}
}
}
You only really to need to reinitialize the $days before each for after the if