$ _GET missing in pagination - php

I have 2 files, the first one:
gives me the list of products
The second one:
- information relating to the product, therefore as an information page
In the first file, I implement a <a> tag, to redirect to the second file
and the variable: $id_evidenza = $row_ListaEvidenze['ID_evidenza'];
<a href="edit_evidenza.php?id=<?php echo $id_evidenza; ?>&te=<?php echo $_GET['te']; ?>" title="Modifica">
<strong><?php echo outputDecode($row_ListaEvidenze['cod_evidenza']); ?></strong>
</a
make a select query, and take my variable:
$myid_processo = "-1";
if (isset($_GET['id'])) {
$myid_processo = $_GET['id'];
}
//42320819($database_riskmanagement,$riskmanagement);
$query_processo = sprintf("SELECT * FROM tev_Evidenze WHERE tev_Evidenze.id_struttura = ".$id_str." AND tev_Evidenze.ID_evidenza = %s", GetSQLValueString($myid_processo, "int"));
$processo = mysqli_query($riskmanagement, $query_processo) or die(mysqli_error($riskmanagement));
createLog($_COOKIE['cod_operatore'], $query_processo);
$row_processo = mysqli_fetch_assoc($processo);
$totalRows_processo = mysqli_num_rows($processo);
with a do / while loop, I show the results on screen and it's ok.
Now the problems begin, because right now from the page where there are the list of products, we are in the product info page, they asked me, to implement a navigation system, which gives the possibility that if I am inside the product A, going back and forth I can scroll through the other products, without going over the product list page, and so I did by implementing this navigation system:
if($_GET['te']==""){
$sel_tipo_acc = " (ev.id_tipo_accreditamento = 0)";
}else{
$sel_tipo_acc = " (ev.id_tipo_accreditamento = ".$_GET['te'].")";
}
$my_ric_att = searchControl(trim($_GET['ric_att']));
$txt_ric = "";
$txt_ric = "Risultati per ";
$r_sql = "SELECT * FROM tev_Evidenze AS ev LEFT JOIN tev_Fatt_crit AS fc
ON fc.ID_fatt_crit = ev.id_fatt_crit
WHERE ev.id_struttura = ".$_SESSION['str']." AND ".$sel_tipo_acc." AND ";
if ($_GET['facr'] != ""){
$r_sql .= " fc.ID_fatt_crit = ".$_GET['facr']." AND ";
}
$r_sql .= " ((ev.cod_evidenza LIKE '%" .$my_ric_att. "%') OR (ev.desc_evidenza LIKE '%" .$my_ric_att. "%')) ";
$txt_ric .= trim($_GET['ric_att']) ;
$r_sql .= " ORDER BY fc.ordine_fatt_crit, ev.cod_evidenza, ev.ordine_evidenza";
$txt_ric .= "<br>";
if($_GET['v']=="all"){
$paginazione = 1;
}else{
$paginazione = 1;
}
$maxRows_ListaEvidenze = $paginazione;
$pageNum_ListaEvidenze = 0;
if (isset($_GET['pageNum_ListaEvidenze'])) {
$pageNum_ListaEvidenze = $_GET['pageNum_ListaEvidenze'];
}
$startRow_ListaEvidenze = $pageNum_ListaEvidenze * $maxRows_ListaEvidenze;
//42320819($database_riskmanagement, $riskmanagement);
$query_ListaEvidenze = $r_sql;
$query_limit_ListaEvidenze = sprintf("%s LIMIT %d, %d", $query_ListaEvidenze, $startRow_ListaEvidenze, $maxRows_ListaEvidenze);
$ListaEvidenze = mysqli_query($riskmanagement, $query_limit_ListaEvidenze) or die(mysqli_error($riskmanagement));
createLog($_COOKIE['cod_operatore'], $v_sql);
$row_processo = mysqli_fetch_assoc($ListaEvidenze);
if (isset($_GET['totalRows_ListaEvidenze'])) {
$totalRows_ListaEvidenze = $_GET['totalRows_ListaEvidenze'];
} else {
$all_ListaEvidenze = mysqli_query($riskmanagement, $query_ListaEvidenze);
$totalRows_ListaEvidenze = mysqli_num_rows($all_ListaEvidenze);
}
$totalPages_ListaEvidenze = ceil($totalRows_ListaEvidenze/$maxRows_ListaEvidenze)-1;
$queryString_ListaEvidenze = "";
if (!empty($_SERVER['QUERY_STRING'])) {
$params = explode("&", $_SERVER['QUERY_STRING']);
$newParams = array();
foreach ($params as $param) {
if (stristr($param, "pageNum_ListaEvidenze") == false &&
stristr($param, "totalRows_ListaEvidenze") == false) {
array_push($newParams, $param);
}
}
if (count($newParams) != 0) {
$queryString_ListaEvidenze = "&" . htmlentities(implode("&", $newParams));
}
}
$queryString_ListaEvidenze = sprintf("&totalRows_ListaEvidenze=%d%s", $totalRows_ListaEvidenze, $queryString_ListaEvidenze);
I have the problem in my url, I can't get all the necessary parameters in $ _GET, that is, if for example I go from product A to that B, I get this:
pageNum_ListaEvidenze=5&totalRows_ListaEvidenze=76&id=340&te=5
pageNum_ListaEvidenze=6&totalRows_ListaEvidenze=76&id=340&te=5
where the only thing that changes is the number after: pageNum_ListaEvidenze=
displaying another record, but the id is always stopped at the first record, I have this problem from this snippet of code, which I posted before:
if (isset($_GET['pageNum_ListaEvidenze'])) {
$pageNum_ListaEvidenze = $_GET['pageNum_ListaEvidenze'];
}
how do i make everything dynamic in the url?

I really understand your issue , but here is a better solution that can make the life easy .
Let's suppose that currently , you are on the info page(Page B as you describe) that show the product information .
To swip for the next product , or previous , you can try to do this :
Normaly , one the info page , you are able to get the id of the current product
$currentProductID = $_GET['id'];
Think to create a method that give you the id of the next product , the query should be like :
SELECT id FROM `product` WHERE `id` > $currentProductID limit 1
This will return the id of the next product , and then redirect to the B page with this id returned using php redirection or by clicking on the tag etc .
To do that for the previous product , just inverse the query above
with <.
Hope that help you .

Related

running a query inside a loop to do another loop

Ok so what i am doing is getting member id's from 1 table and looping those ID's through another table to get values to output. I had it working going through the first loop, then notice the output was all screwy, so released I needed to loop it through again, since there will could be multiple entries in the 2nd query for MemID. now I put in the 2nd loop but its not even going through, not sure where I messed up the code, but doesn't seem to output now when running it through the 2nd loop. though it did output without the loop. but that won't work due to multiple rows for each $memid.
$qry_skamembers = "SELECT * FROM ap_skamembers ORDER BY id";
$qry_skamembers = $mysqli->real_escape_string($qry_skamembers);
if($result_skamembers = $mysqli->query($qry_skamembers)){
while($row_skamembers = $result_skamembers->fetch_array()){
$AffID = $row_skamembers['AffID'];
$MemID = $row_skamembers['MemberID'];
$skacon = new mysqli(OW_DB_HOST, OW_DB_USER, OW_DB_PASSWORD, OW_DB_NAME);
if ($skacon->connect_error) {
die('Connect Error');
}
$get_data = "SELECT * FROM ow_base_billing_sale WHERE userID = $MemID AND status = 'delivered' ORDER BY id";
$get_data = $skacon->real_escape_string($get_data);
if($result_data = $skacon->query($get_data)){
while($finish = $result_data->fetch_array()){
$test = $finish['status'];
if($test == 'delivered') {
$sale_amount = $finish['price'];
$product = $finish['transactionUId'];
$products = mysqli_fetch_assoc(mysqli_query($mysqli, "SELECT * FROM ap_earnings where product = $product"));
if(mysqli_num_rows($products) > 0) { }
else {
echo "AFF: " . $AffID . " | ";
echo "Mem: " . $MemID . " | ";
echo "PRICE: " . $sale_amount . " | ";
echo "PRODUCT: " . $product . " -- ";
include('controller/record-sale.php');
echo "inserting record";
echo "run finished <br><br>";
}
}
}
}
}
}
I am still rather new at coding, so it might look a bit sloppy, my apologies for that.
I do not know if that is ist bu try to replace:
$get_data = $skacon-->real_escape_string($get_data);
with
$get_data = $skacon->real_escape_string($get_data);
i think there is an extra -
And as we found out in comments you need to change $product to '$product'
You can do all that in one query,nevermind it will be much faster
SELECT aps.AffID,aps.MemberID,owb.price,owb.transactionUId
FROM db1.ap_skamembers aps JOIN db2.ow_base_billing_sale owb
ON aps.MemberID = owb.userID AND owb.status='delivered'
JOIN db3.ap_earnings ape
ON ape.product = owb.transactionUId
ORDER BY aps.id

How to display count results with multiple keywords anywhere in a database field

We have a page tcount.php where we fetch counts for BOTH keyword1 and keyword2 occuring anywhere in a text field in mysql database using php script. The counts are displayed as hyperlinks. Now after that, we want that if someone clicks on the hyperlinks, they will see the detailed results in showt.php page showing those rows of the database corresponding to only those text field containing BOTH keywords.
The url of the second page showt.php is like
http://www.example.com/page.php?keyword=keyword1+keyword2
But problem is that it shows only those results which have keyword1 and keyword2 next to each other.
For example, keyword1 is car and keyword2 is cap and our text fields are as follows -
car cap
car best cap
car new
Then, we want it to show 1. and 2. as results but it is showing only no. 1 in the results page.
Please help.
Edit -
This is the code in page 1 tcount.php -
$kewyWordQ = $db->query("SELECT keywords FROM Table1 ");
<?php
while($row = $kewyWordQ->fetch(PDO::FETCH_ASSOC))
{$keyWord = $row['keywords'];
$keyWordsArr = explode(" ", $row['keywords']);
$countData = array();
$keyIndex = 0;
$tIndices = array();
$tArr = array();
$tIndices[] = "-1";
foreach($keyWordsArr as $keyword)
{
$t = $db->query("SELECT user_name FROM Table2 WHERE
t_text LIKE '%$keyWordsArr[$keyIndex]%'");
$tArr[] = $t;
while($row2 = $tweet->fetch(PDO::FETCH_ASSOC))
{
$found = TRUE;
foreach($keyWordsArr as $keyword1)
{
$ret = strpos(strtolower($row2['t_text']),
strtolower($keyword1));
if(($ret == 0) &&
strcmp(strtolower($row2['t_text'][0], strtolower($keyword1)[0])))
{
$found = FALSE;
break;
}
}
if($found == TRUE)
{
$ret = strpos($tIndices, $row2['t_id']);
if(($ret == 0) && strcmp($tIndices[0],
$row2['t_id']))
{
$tIndices[] = $row2['t_id'];
$countData[] = $row2['user_name'];
}
}
}
$keyIndex++;
}
?>
<tr><td><?php echo $row['keywords'];?></td>
<td><a href="showt.php?keyword=<?php echo
urlencode($keyWord); ?>" target="_blank"><?php echo count($countData); ?
></a></td>
<td><a href="showt.php?keyword=<?php echo
urlencode($keyWord); ?>" target="_blank"><?php echo
count(array_unique($countData)); ?></a></td>
</tr>
<?php } ?>
And this is the code in page 2 showt.php -
$keywords = $_GET['keyword'];
$sql="SELECT col1, col2, col3 from t AS s INNER JOIN users AS p ON
s.user_name=p.user_name where s.t_text LIKE '%$keywords%'
The WHERE statement of your query should look like:
WHERE my_text_field LIKE ?
and the binded parameter should be %$keyword1%$keyword2%
In order to define the $keyword1 and $keyword2 variables you can do something like:
list($keyword1, $keyword2) = explode(' ', $_GET['keyword']);
or you can simply use "%" . implode('%', explode(' ', $_GET['keyword'])) . "%" in case you have multiple possible keywords
There is a two way
one is hard way doing by php and mysql
$keyword = $_GET('keyword');
$keywordArray = explode(" ",$keyword);
$queryString = "";
foreach($keywordArray as $key=>$value) {
$queryString .= " column_name LIKE '%$value%' OR";
}
"SElECT * FROM table WHERE ".$queryString
second is mysql itself, that is Full text search

table updates empty spaces when user do not enter anything to the textbox

i am doing a project where one may update the name, position, department and tag of the employee.
But as i do my project, it wont update, i know there is something wrong with my code. would you guys mind checking it.
my php page has an index.php which is the main menu, if you click the employee name in the list, a pop up window will appear. that pop up is for updating.
my php code (it now updating) but errors found:
<?php
$con=mysql_connect('localhost','root','pss') or die(mysql_error());
mysql_select_db('intra',$con);
if(isset($_POST['submitted']))
{
$sql = "SELECT * FROM gpl_employees_list where emp_id='".$_POST['eid']."'";
$result = mysql_query($sql) or die (mysql_error());
if(!$result || mysql_num_rows($result) <= 0)
{
return false;
}
$qry = "UPDATE gpl_employees_list SET emp_nme = '".$_POST['ename']."', emp_pos = '".$_POST['pos']."', emp_dep = '".$_POST['dep']."', emp_tag = '".$_POST['tag']."' WHERE emp_id = '".$_POST['eid']."' ";
mysql_query($qry) or die (mysql_error());
?><script>window.close();</script><?php
}
?>
*NOTE : this is now updating, but if a user leaves one of the textboxes empty, it updates the table with empty spaces as well and that is my problem now. how do i avoid that? i mean if a user leaves one textbox empty,the data with empty values must still contain its old value,but how to do that with this code? thanks for those who will help
MisaChan
You use $_POST for 'name/pos/dep/tag' and $_GET for 'emp' so you're probably not getting the values.
Change the GETs to POST - that should do it.
Since you're updating, I'd recommend using POST over GET.
GET is more appropriate for searching.
Also, you can put all your update queries into one update query.
Like so.
$name = $_POST['name'];
$pos = $_POST['pos'];
$dep = $_POST['dep'];
$tag = $_POST['tag'];
$emp = $_POST['emp'];
$qry_start = "UPDATE gpl_employees_list SET ";
$where = " WHERE emp_id = $emp";
$fields = "";
$updates = "";
if($name){
$updates .= " `emp_name` = $name,";
}
if($pos){
$updates .= " `emp_pos` = $pos,";
}
if($dep){
$updates .= " `emp_dep` = $dep,";
}
if($tag){
$updates .= " `emp_tag` = $tag,";
}
$updates = substr($updates, 0, -1); //To get rid of the trailing comma.
$qry = $qry_start . $updates . $where;
this is what i used to keep it working :) i hope this could be a source for others as well :)
$col['emp_nme'] = (trim($_POST['ename']))?trim($_POST['ename']):false;
$col['emp_pos'] = (trim($_POST['pos']))?trim($_POST['pos']):false;
$col['emp_dep'] = (trim($_POST['dep']))?trim($_POST['dep']):false;
$col['emp_tag'] = (trim($_POST['tag']))?trim($_POST['tag']):false;
// add a val in $col[] with key=column name for each corresponding $_POST val
$queryString ="UPDATE `gpl_employees_list` SET ";
foreach($col as $key => $val){
if($val){
$queryString .="`".$key."`='".$val."',";
}
}
$queryString = substr($queryString ,0 ,strlen($queryString) - 1 )." WHERE emp_id = '".$_POST['eid']."'";
mysql_query($queryString);
After making changes to an SQL database, remember to commit those changes, otherwise they'll be ignored.

PHP/MySQL pagination going wrong

Using PHP on my website linking to a library database in MySQL. The one area I can't seem to get right is the pagination of results. I've tried about twenty different code snippets and have the same problem each time - can't get more than the first page of results to display. Despite reading lots of forum posts on this one, can't get past it. My select query is slightly more complex in that several keywords can be combined and it is searching multiple fields. When results are displayed, they also pull data from different tables. I really hope someone can spot where I'm going wrong. Switch statement used dependent on which type of search the user requests, so the code for one case given below.
$term = trim($_REQUEST['term']);
$searchterm = mysql_real_escape_string($term, $link);
$index = $_REQUEST['index'];
switch ($index)
{
case "title":
$array = explode(" ", $searchterm);
$sql = "select identifier, title, publication_date from publication where";
foreach ($array as $key => $keyword) {
$sql .= " (title like '%$keyword%' or alternative_title like '%$keyword%')";
if ($key != (sizeof($array) - 1)) $sql .= " and ";
if ($key == (sizeof($array) - 1)) $sql .= " order by title";
}
if(!$result = mysql_query($sql, $link)) {
showerror();
}
else {
$numrows = mysql_num_rows($result);
if ($numrows == 0) {
echo "<h2>No records found</h2>";
}
//start pagination
$perPage = 10;
$page = (isset($_REQUEST['page'])) ? (int)$_REQUEST['page'] : 1;
$startAt = $perPage * ($page - 1);
$totalPages = ceil($numrows / $perPage);
$links = "";
for ($i = 1; $i <= $totalPages; $i++) {
$links .= ($i != $page ) ? " <a href='search.php?page=$i&search=$term'>
Page $i</a> " : "$page ";
}
echo "<h3>Displaying page $page of $totalPages:</h3><br />";
$counter = 1;
$sql = "select identifier, title, publication_date from publication where";
foreach ($array as $key => $keyword) {
$sql .= " (title like '%$keyword%' or alternative_title like '%$keyword%')";
if ($key != (sizeof($array) - 1)) $sql .= " and ";
if ($key == (sizeof($array) - 1)) $sql .= " order by title
LIMIT $startAt, $perPage";
}
$result = mysql_query($sql, $link);
echo "<table class=\"results\">\n";
while($row = mysql_fetch_array($result))
{
//echo data
}
echo "</table><br />\n";
echo $links; // show links to other pages
echo "<p> </p>";
}
break;
as stated above, -1 vote for placing someone elses code instead of trying it yourself. This code is wayyyy to much for what a pagination script should do. You could have added more specific code snippet and a better question. I'll try to take a look at it however.
As you can't get further than page 1 it seems that somethings going wrong aroung $page = (isset($_REQUEST['page'])) ? (int)$_REQUEST['page'] : 1 ; or a little below. Try echoƫing your SQL code for each page and take a look if the LIMIT is right or that it stays the same, probably the last. At least that gives you a starting point from where to take a look in your code.
Does it give you the right amount of links to go to?

Stumped in the middle of a PHP loop

Here's what I've got so far-
$awards_sql_1 = mysql_query('SELECT * FROM categories WHERE section_id = 1') or die(mysql_error());
$awards_sql_2 = mysql_query('SELECT * FROM categories WHERE section_id = 2') or die(mysql_error());
$awards_sql_3 = mysql_query('SELECT * FROM categories WHERE section_id = 3') or die(mysql_error());
$awards_sql_4 = mysql_query('SELECT * FROM categories WHERE section_id = 4') or die(mysql_error());
$loop = 1;
while($row_sections = mysql_fetch_array($sections_query)) {
$category = 1;
echo "<h3>" . $row_sections['section_name'] . " (Loop# $loop)</h3>";
while($categories = mysql_fetch_array(${"awards_sql_{$loop}"})) {
${"winners_sql_{$loop}"} = mysql_query("SELECT * FROM 2009_RKR_bestof WHERE section = $loop && category = $category ORDER BY result_level ASC") or die(mysql_error());
echo "<h4><strong>{$categories['category_name']}</strong></h4>";
echo "<ul class=\"winners\">";
>> while($winners = mysql_fetch_array(${"winners_sql_{$loop}"})) {
switch ($winners['result_level']) {
case 1: $result_level = "Platinum"; break;
case 2: $result_level = "Gold"; break;
case 3: $result_level = "Silver"; break;
}
if (isset($winners['url'])) { $anchor = ""; $close = ""; }
echo "<li>$anchor{$winners['winner']}$close ($result_level)</li>";
unset($anchor);
unset($close);
}
echo "</ul>";
$category++;
}
$loop++;
}
Where I'm getting stumped, is I'm getting this thing to loop through correctly, my loop counter ($loop) is working, but when it gets time to spit out the actual reward recipients after the first loop through winners, it's only producing the category titles, the list-items are not getting looped out.
I added a little pointer to where I think the problem begins or centers around (>>).
My guess is I need to maybe unset a var somewhere, but I don't know, I can't see it.
I'm with KM - you're displaying a single page and with your loops, you've got a LOT of queries happening at once - what if 1,000 people hit that page at the same time? ouch...
Maybe consider a larger query (with some repeated data) and loop through it once?
For example:
SELECT
section_name,
category_name,
result_level,
url,
winner
FROM 2009_RKR_bestof
INNER JOIN categories ON 2009_RKR_bestof.category = categories.id
INNER JOIN sections ON 2009_RKR_bestof.section = sections.id
ORDER BY section_name,category_name ASC
In your loop, you can do checks to determine if you're in a new section (category/whatever):
//pseudo-code
$current_section = "";
while($stuff = mysql_fetch_array($sql))
{
if ($current_section == "")
{
$current_section = $stuff["section_name"];
}
if ($current_section == $stuff["section_name"])
{
//keep going in your loop
}
else
{
//we've gotten to a new section - so close your html and start a new section
}
}
You get the idea..
My guess would be that it is a data problem. It isn't having trouble reading the titles, only the winners. If it iterated once, I would check the data, and ensure that winners_sql_2 - winnders_sql_4 are getting actual data. Perhaps add an echo winners_sql_2 line, to output the contents of the query, and ensure the query is framed correctly.

Categories