how to make static index of array in php - php

I am trying to store values from form radio to array. But problem which i am facing is that every time array 1st index is replaced with new value. I believe this is scope problem. I also tried to declare global array but no success.
Here is the code:
<?php
include_once("connection.php");
$c = new DBcon();
$c->startcon();
global $array; // not effecive
// $q = $_POST['t'];
// echo 'fff', $q;
$page = $_GET['page'];
echo 'pagesss', $page, 'ppp';
if ($page == "") {
$page = "1";
} else {
// If page is set, let's get it
$page = $_GET['page'];
}
// Now lets get all messages from your database
$sql = "SELECT * FROM quizes";
$query = mysql_query($sql);
// Lets count all messages
$num = mysql_num_rows($query);
// Lets set how many messages we want to display
$per_page = "2";
// Now we must calculate the last page
$last_page = $num;
echo 's', $num;
// And set the first page
$first_page = "1";
// Here we are making the "First page" link
echo "<a href='?page=" . $first_page . "'>First page</a> ";
// If page is 1 then remove link from "Previous" word
if ($page == $first_page) {
echo "Previous ";
} else {
if (!isset($page)) {
echo "Previous ";
} else {
// But if page is set and it's not 1.. Lets add link to previous word to take us back by one page
$previous = $page - 1;
echo "<a href='?page=" . $previous . "'>Previous</a> ";
}
}
// If the page is last page.. lets remove "Next" link
if ($page == $last_page) {
echo "Next ";
} else {
// If page is not set or it is set and it's not the last page.. lets add link to this word so we can go to the next page
if (!isset($page)) {
$next = $first_page + 1;
echo "<a href='?page=" . $next . "'>Next</a> ";
} else {
$next = $page + 1;
echo "<a href='?page=" . $next . "'>Next</a> ";
}
}
// And now lets add the "Last page" link
echo "<a href='?page=" . $last_page . "'>Last page</a>";
// Math.. It gets us the start number of message that will be displayed
$start = ($page * ($page - 1)) / $page;
echo 'start', $start;
echo 'page', $page;
// Now lets set the limit for our query
$limit = "LIMIT $start, $per_page";
// It's time for getting our messages
$sql = "SELECT * FROM quizes $limit";
$query = mysql_query($sql);
echo "<br /><br />";
// And lets display our messages
$i = 0;
$l = 0;
while ($row = mysql_fetch_array($query) or die(mysql_error())) {
$a = $row['A'];
echo '<form method="get" action="?page=".$next."">';
while ($row = mysql_fetch_array($query)) {
echo '<div class="boxed" >';
echo "\t" . '<tr><th>' .
$row['question'] . "<br>" .
'</th><th>' . "<input type='radio' name= 't[]' value='{$row['A']}'>" . $row['A'] . "<br>" .
'</th><th>' . "<input type='radio' name='t[]' value='{$row['B']}'>" . $row['B'] . "<br>" .
'</th><th>' . "<input type='radio' name='t[]' value='{$row['C']}'>" . $row['C'] . "<br>" .
'</th><th>' . "<input type='radio' name='t[]' value='{$row['D']}'>" . $row['D'] . '</th>
</tr>';
echo '<input type="hidden" name="page" value="' . $next . '">';
echo '<input type="submit" name="submit"/>';
$i++;
echo '</div>';
echo '</div>';
}
echo '</form>';
if (isset($_GET['submit'])) {
$example = $_GET['t'];
foreach ($example as $value) {
$array[$i++] = ($value);
echo "$array[0] <br>"; // printing correct statement but replacing old values with new value everytime.
echo "$array[1] <br>"; // 0 values
echo "$array[2] <br>"; // 0 values
}
}
}
?>
I have seen these posts: PHP array indexing: $array[$index] vs $array["$index"] vs $array["{$index}"] , PHP - define static array of objects but no help. Kindly help what should i do?

You cannot do
$array[$i++]
this will always be $array[1]
instead do
$i++;
$array[$i]= $value;
P.S. $array is a terrible name for a variable...

if (isset($_GET['submit'])) {
$example = $_GET['t'];
$i=0;
$arrayA = array();
foreach ($example as $value) {
$arrayA[$i] = ($value);
$i++;
}
print_r($arrayA);
}

if you do
$array[$i++] ;
it wont work , just try this and it wont replace your old value
$array[$i] = $value;
$i++;

You must increment your variable first, then use the variable as the array key.
Edit: this is what you're looking for:
$i = 0;
foreach ($example as $value) {
$array[$i] = $value;
$i++;
}

Related

Count row and repeat the same rows within Loop

I'm working on mansory gallery here images fetching into the row first row contains three images and then for the second row contains two images and so on.
Now currently all images coming inside same row. I want to add in a loop I had tried but unable to achieve the result. For inspiration link
<?php
include('admin/config.php');
$result = mysqli_query($db, "SELECT * FROM gallery order by id desc");
// var_dump($result->num_rows);
while ($row = mysqli_fetch_array($result)) {
echo "<div class='gallery-items'>";
echo "<div class='mansory-item'>";
echo "<a href='admin/images/".$row['path']."' data-lightbox='gallery' class='ansa-thumb'>";
echo "<img src='admin/images/".$row['path']."' class='item-img img-1'>";
echo "</a>";
echo "</div>";
echo "</div>";
}
?>
Current output
Expected output
Can anyone suggest me how should i get this output.
Check below snippet,
$inc = 4;
$i = 1;
while ($row = mysqli_fetch_array($result)) {
if (empty($temp) || $inc != $temp) {
$temp = $inc;
if ($inc == 4) {
echo "<div class='gallery-grid'>";
}
echo "<div class='gallery-items'>";
}
if ($i <= $inc) {
// echo $i . '<>';
echo "<div class='mansory-item'>";
echo "<a href='admin/images/" . $row['username'] . "' data-lightbox='gallery' class='ansa-thumb'>";
echo "<img src='admin/images/" . $row['username'] . "' class='item-img img-1'>";
echo "</a>";
echo "</div>";
$i++;
}
if ($i == $inc) {
echo "</div>";
if ($i == 3) {
echo "</div>";
}
$i = 1;
$inc = ($inc == 4 ? 3 : 4);
}
}

Limiting bootstrap pagination in PHP to 5 pages

I'm trying to create pagination in PHP where 5 pages are displayed.
When on the first page we have:
[1][2][3][4][5] ...[325][>>]
Clicking on [325] will take you to that page (the last record), clicking on the right arrow will take you to page [2].
When on the second page we have:
[<<][1]...[2][3][4][5][6] ...[325][>>]
And when on the last page we have:
[<<][1]...[321][322][323][324][325]
I've been researching on how to do this without much luck. I think I understand that I need to create an array with adjacent pages of 2 on each side of the active page, when we are on any page except the first or last page. I also need to create an <li>1</li>
and
<li><?php echo $last_record; ?></li>
for when a user is anywhere but the first or last record.
I have the following code which works great, however when we start getting a large number of records, the pagination count gets ridiculous.
<ul class="pagination pull-left pagination-md">
<?php
// Creates back button in pagination
if(isset($page)) {
if($page > 1) {
$page_minus = $page-1;
echo "<li><a href='blog.php?page=$page_minus'> « </a></li>";
}
}
?>
<?php
global $con;
$q_pagination = mysqli_prepare($con, "SELECT COUNT(*) FROM admin_panel WHERE ");
$q_pagination->execute();
$result_pagination = $q_pagination->get_result();
$rows_result = $result_pagination->fetch_array();
$total_rows = array_shift($rows_result);
$post_per_page = $total_rows/15;
$post_per_page = ceil($post_per_page);
for($i = 1; $i <= $post_per_page; $i++) {
if(isset($page)){
if($i == $page) {
echo "<li class='active'><a href='blog.php?page=$i'>$i</a></li>";
}
else {
echo "<li><a href='blog.php?page=$i'>$i</a></li>";
}
}
}
// Creates the forward button in pagination
if(isset($page)){
if($page+1 <= $post_per_page) {
$page_plus = $page+1;
echo "<li><a href='blog.php?page=$page_plus'> » </a></li>";
}
}
?>
</ul>
I'll admit, after researching and attempting to make this work I'm just getting twisted in the logic. Does anyone have any thoughts on how to best approach this? Leads, current examples, etc. Most of what I've found is dated, incomplete, or stupid long.
<?php
session_start();
include "mysqli_connect.php";
$companyID = $_SESSION['compid'];
$db = new Database();
$dbc = $db->getConnection();
$display = 3; //number of records per page
$pages;
$dbb = new Database();
$dbcb = $dbb->getConnection();
$stat = "select * from reservationStatus where resStatId = '$companyID' ";
$r = mysqli_query($dbcb, $stat);
//variable for sorting - default is for registration date
$sort = (isset($_GET['sort'])) ? $_GET['sort'] : 'rd';
switch ($sort)
{
case 'ln':
$orderby = 'uniquenumber ASC';
break;
case 'fn':
$orderby = 'status ASC';
break;
case 'rd':
$orderby = 'resId ASC';
break;
case 'em' :
$orderby = 'resDate ASC';
break;
default:
$orderby = 'resId ASC';
break;
}
if(isset($_GET['p']) ) //already calculated
{
$pages=$_GET['p'];
}
else
{
//get the total number of records from the table
$q = "select count(resId) from reservation where companyID = '$companyID'";
$r = mysqli_query($dbc, $q);
$row = mysqli_fetch_array($r, MYSQLI_NUM);
$records=$row[0];
if($records > $display ) //$display is the number of records per page
//ceil rounds fractions up to integer value
$pages=ceil($records/$display);
else
$pages = 1;
}
//now determine where in the database to start
if(isset($_GET['s']) ) //already calculated
$start=$_GET['s'];
else
$start = 0;
//$q = "select * from users LIMIT $start, $display";
$q = "select * from reservation where companyID = '$companyID' order by $orderby LIMIT $start, $display";
$r = mysqli_query($dbc, $q);
if($r)
{
echo '<br />';
//display a table of results
echo '<div class="container">';
echo '<h1> Your Orders </h1>';
echo '<table align="center" class="table table-bordered table-striped" width="60%">';
echo '<tr bgcolor="#87CEEB">
<td><b>View</b></td>
<td><b>Change Status</b></td>
<td><b> Reference Number</b></td>
<td><b>Status</b></td>
<td><b>Date</b></td>
<td><b>Total Price</b></td></tr>';
//above is the header
//loop below adds the user details
//use the following to set alternate backgrounds
$bg = '#eeeeee';
while($row = mysqli_fetch_array($r))
{
$stat = "select * from reservationStatus where resStatusId = $row[7] ";
$rr = mysqli_query($dbcb, $stat);
$roww = mysqli_fetch_array($rr);
$bg = ($bg=='#eeeeee' ? '#ffffff' : '#eeeeee');
echo '<tr bgcolor="' . $bg. '">
<td>View</td>
<td>Change Status </td>
<td>'.$row[2].'</td>
<td>'.$roww[1].'</td>
<td>'.$row[1]. ' ' . $row[8].'</td>
<td>'.$row[3].'</td>
</tr>';
}
echo '</table></div>';
}
else
{
echo '<p class="error">' . $q . '</p>';
echo '<p class="error"> Oh dear. There was an error</p>';
echo '<p class="error">' . mysqli_error($dbc) .'</p>';
}
mysqli_free_result($r);
//makes links to other pages if required
if($pages > 1)
{
echo '<br /><p> ' ;
//find out what page we are on
$currentpage = ($start/$display)+1;
//need a previous button if not first page
if($currentpage != 1)
{
echo ' <a href="viewOrdersForCompanies.php?$s=' . ($start - $display) .
'&p=' .$pages . '&sort='.$sort.'">&nbspPrevious&nbsp</a>';
}
//create the numbered pages
for($i = 1; $i <= $pages; $i++)
{
if($i != $currentpage)
{
//the 's' paramater is used in the link to determine which the value
// in the LIMIT clause used in the select statement near the top of the page
echo '<a href="viewOrdersForCompanies.php?s=' . (($display * ($i-1))) . '&p='
. $pages . '&sort='.$sort.'">&nbsp' . $i . '&nbsp</a>';
}
//&nbsp is a character to insert a whitespace
}
//if not last page create next button
if($currentpage != $pages)
{
echo '<a href="viewOrdersForCompanies.php?s=' . ($start+$display) . '&p=' . $pages
. '&sort='.$sort.'">&nbspNext&nbsp</a>';
}
echo '</p>';
}
?>

PHP - Search results not paginating

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.

GET method in fetching values and display data according to categories

I'm working on an online menu ordering system and I wanted to filter the data according to its category. I've tried to make it work with this code but it's only displaying one category.
**<li><?php echo "<a href='clubmarumenu.php?choice=".$category."'>"?> Scotch/Bourbon</a></li>
<li><?php echo "<a href='clubmarumenu.php?choice=".$category."'>"?> Brandy/Cognac</a></li>
<li><?php echo "<a href='clubmarumenu.php?choice=".$category."'>"?> Vodka/Gin/Tequila/Apertifs/Liqueur</a></li><br>
<li><?php echo "<a href='clubmarumenu.php?choice=".$category."'>"?> Beer/Softdrinks</a></li>
<li><?php echo "<a href='clubmarumenu.php?choice=".$category."'>"?> Cocktails</a></li>**
^ basically these are the categories and below is how display them.
**
<?php
$category = $_GET['choice'];
$category = str_replace('%', ' ', $category);
$query = "SELECT * FROM product_drinks WHERE drinks_cat = '" . $category . "'";
$result = mysql_query($query);
$total_records = mysql_num_rows($result); // the number of records in your result set
$num_cols = 2; // the number of columns
$num_rows = ceil($total_records / $num_cols); // the number of rows
$num = 0; // don't change this value, this is the first number of each record inside a record set
echo "<table style= 'cellpadding:8 width:100'>\n";
// next the loop for the table rows
for ($rows = 0; $rows < $num_rows; $rows++) {
echo "<tr bgcolor='black'>\n";
// this is the loop for the table columns
for ($cols = 0; $cols < $num_cols; $cols++) {
if ($num < $total_records) { // show records if available (reduce by one because the first record is no. "0" (zero)
// first create variables with the values of the current record
$title = mysql_result($result, $num, "drinks_name");
$clean_name = str_replace('_', ' ', $title);
$price = mysql_result($result, $num, "drinks_shot");
$price2 = mysql_result($result, $num, "drinks_bottle");
$category = mysql_result($result, $num, "drinks_cat");
$description = mysql_result($result, $num, "drinks_image");
$title = str_replace(' ', '%', $title);
echo "<td class='label'><a class='fancybox fancybox.ajax' href='food.php?drink=" . $title . "'>
<img src='" . mysql_result($result, $num, 'drinks_image') . "' class='masterTooltip' title= '" . $category . "'</a><br>";
echo "<td style='width:50%' class='desc'><b>" . $clean_name . "</b><br> Shot:<font style='color:#0072bc'> Php " . $price . "</font><br> Bottle: <font style='color:#724c0e'>Php " . $price2 . "</font></td>\n";
} else { // show an empty cell
echo "<td> </td>\n";
}
$num++; // raise the number by one for the next record
}
echo "</tr>\n"; // there are no more cols in this row, close the table row tag
}
echo "</table>\n"; // end of the region = closing tag for the table element
?>
**
I wish I could get over this wall. Please help~
First things first.
<?php echo "<a href='clubmarumenu.php?choice=".$category."'>"?>
In the first chunk of code, you are using the same variable for all the links.
Are you passing different values for $category here. I believe you are not! and hence all the links are pointing to the same url.
You should use urldecode instead of str_replace('%', ' ', $category). (http://in2.php.net/urldecode)
Please indent your code so that it can be read and understood easily :)

add an if echo statement to my search engine

I have a search engine and because of the paralympics, I want people to be able to see a h1 countdown I have placed at the top of my site. Underneath will be the looped results from my database. Any ideas where I go wrong? because in this if, it won't echo the h1 tag at all. I would like to above my results.
$query = " SELECT * FROM scan WHERE ";
$terms = array_map('mysql_real_escape_string', $terms);
$i = 0;
foreach ($terms as $each) {
if ($i++ !== 0) {
$query .= " OR ";
}
$query .= "keywords LIKE '%{$each}%'";
}
// Don't append the ORDER BY until after the loop
$query .= "ORDER BY rank";
$query = mysql_query($query) or die('MySQL Query Error: ' . mysql_error($connect));
$numrows = mysql_num_rows($query);
if ($numrows > 0) {
while ($row = mysql_fetch_assoc($query)) {
$id = $row['id'];
$title = $row['title'];
$description = $row['description'];
$keywords = $row['keywords'];
$link = $row['link'];
$rank = $row['rank'];
echo '<h2><a class="ok" href="' . $link . '">' . $title . '</a></h2>' . PHP_EOL;
echo '<p maxlength="10" class="kk">' . $description . '</p>' . PHP_EOL;
echo '<p><a class="okay" href="' . $link . '">' . $link . '<br><br><span class="keywords"></p>' . PHP_EOL;
}
} else {
echo "No results found for \"<b>{$k}</b>\"";
}
if ($k = "Paralympics 2012") {
echo "<h1> Countdown to Paralympics: 7 Days </h1>";
}
if ($k = "Paralympics 2012") {
echo "<h1> Countdown to Paralympics: 7 Days </h1>";
}
Will always print the <h1>. You're doing assignment rather than comparison. Try:
if ($k == "Paralympics 2012")
Also, verify that $k is what you expect it to be when debugging.
One equals (=) assigns, and two/three (==/===) compares. The line
if ($k = "Paralympics 2012") {
Assigns $k to a string, which always returns true, because any string other than an empty one ("") is truthy. Try this:
if ($k === "Paralympics 2012") {
First things first, the <h1> is always displaying, opposite of what you're question states. It's always displaying due to the fact that you're doing an assignment of a non-false value with:
if ($k = "Paralympics 2012") {
Update that to use a comparison to fix that logic issue.
if ($k == "Paralympics 2012") {
Next, to get it to display above your results, you need to actually move that if-statement above the loop that echos the results. Try placing it in the if ($numrows > 0) { block, like this:
if ($numrows > 0) {
if ($k == "Paralympics 2012") {
echo "<h1> Countdown to Paralympics: 7 Days </h1>";
}
while ($row = mysql_fetch_assoc($query)) {
...

Categories