if else statement with loop in while loop/php - php

I will admit right now I have gone through all of the posts though I went through to 2008. My problem is that the if else statement is only receiving one row and calling all the others false off of both of the while loops or receives 2 when you use the form. I am trying to see if in all the rows if a item is bought using 2 different databases. Here is the code.
$id2 = $_SESSION['id'];
$naturesql = mysql_query("SELECT * FROM backgrounds WHERE type=2");
while($row = mysql_fetch_array($naturesql)) {
$id = $row['id'];
$name = $row['name'];
$background = $row['background'];
$pic = $row['image'];
$check = mysql_query("SELECT * FROM store_items WHERE userid='$id2'");
while($checkrow = mysql_fetch_array($check)) {
$types = $checkrow['type2'];
}
if($id == $types) {
$bought = 'This item has already been bought';
} else {
$bought = '<form>
</form>';
// this form works fine
}
$display .= '<table width="100%"><tr><td><center><font size="+1">' . $name . '</font></center></td></tr><tr><td><center><img src="' . $pic . '" width="80px"></img></center></td></tr><tr><td>' . $bought . ' </td></tr></table>';
}
...
<?php echo $display ?>
What shows up.
1st result
Name 1
Pic 1
form shows up here
2nd result
Name 2
Pic 2
form also shows up here
3rd and last result
Name 3
Pic 3
This item has already been bought
This is what I get when I look on the page. If I bought a item this is what I get lets say 1st item.
1st result
Name 1
Pic 1
This item has already been bought
2nd result
Name 2
Pic 2
form also shows up here
3rd and last result
Name 3
Pic 3
This item has already been bought
It pops this up. Though when I refresh turns back into the the 1st one I shown only showing 1 result. Any thoughts why not working with the others.
It should be like this if you bought all but is not
1st result
Name 1
Pic 1
This item has already been bought
2nd result
Name 2
Pic 2
This item has already been bought
3rd and last result
Name 3
Pic 3
This item has already been bought
My only other question is there an alternative to this so keeps the loop and checks if the statement is true or not like a if else statement. If I can't do it with if else statement.

First of all you can summarize this in 1 query (it's not in 2 database, but in 2 tables it seems from your code)
SELECT b.*, s.type2 AS store_items_type2
FROM backgrounds AS b
LEFT JOIN store_items AS s ON (s.type2 = b.id AND s.userid='$id2')
WHERE b.type=2
How come $id2 = $_SESSION['id'];? A session ID is not the same as a user ID..
You should try to put a little more effort in constructing your question and the code, to make it more understandable for us.

I can't post everything on here though here should give some in site what I did to get this to work. Surprisingly it worked like a charm. Note to everyone putting in 2 tables in one mysql_query didn't help at all it just made things worse. So I wouldn't advise it for this.
Simple version I did
$id = $_SESSION[id];
$check = mysql_query("SELECT * FROM store_items WHERE userid='$id2'");
while($checkrow = mysql_fetch_array($check)){
$types = $checkrow['type2'];
}
$naturesql = mysql_query("SELECT * FROM backgrounds WHERE type=2");
while($row = mysql_fetch_array($naturesql)) {
$id = $row['id'];
$name = $row['name'];
$background = $row['background'];
$pic = $row['image'];
$check = mysql_query("SELECT * FROM store_items WHERE userid='$id2' AND type=2 AND type2='$id' AND other='$pic'");
while($checkrow = mysql_fetch_array($check)) {
$types = $checkrow['type2'];
}
if($id == $types) {
$bought = 'This item has already been bought';
} else {
$bought = '<form>
</form>';
// this form works fine
}
$display .= '<table width="100%"><tr><td><center><font size="+1">' . $name . '</font></center></td></tr><tr><td><center><img src="' . $pic . '" width="80px"></img></center></td></tr><tr><td>' . $bought . ' </td></tr></table>';
}
Like I promised I would post if I figured it out. Might of toke a little longer then I hoped but well there you go.

Related

$ _GET missing in pagination

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 .

checking urls against tables in the database

i am currently using url rewrite via IIS which is working and i am capturing the url with the below variable
$compiled_url= $_GET["params"];
however i need to check whats in that url with whats in the pages table in MySQL. the table looks like the below
tbl_pages
page_id | page_slug | page_parent
--------+-----------+------------
1 | posts | 0
2 | daily | 2
http://www.domain.com/posts/daily
what possible methods are there to check the above domain and passed parameters against the database and make sure they exist in that order so if the url was typed backwards daily/posts it would fail to a 404 as they don't reflect that way in the database
i have started with this method but just as an example my end result i would like to be a class or a neater option
$compiled_url = explode("/",$compiled_url);
$compiled_parent=0;
foreach($compiled_url as $url_decompiled)
{
$url_results = mysqli_query($webapp_db,"SELECT * FROM tbl_pages WHERE page_slug='" . $url_decompiled . "' AND page_parent ='" . $compiled_parent . "'");
if(mysqli_num_rows($url_results) > 0)
{
echo "page found <br>";
$result = mysqli_fetch_array($url_results);
$compiled_parent=$result['page_id'];
}
else
{
echo "page not found <br>";
break;
}
}
who has done something like this before? what methods are available without using a framework?
You can use something like this (have not tested it), but you get the gist of it...
<?php
$compiled_url = explode("/",$compiled_url);
// using alphabet characters for table aliases
$alphabet = explode("","abcdefghiklmnopqrstuvwxyz");
$sql_query = "SELECT * FROM tbl_pages ".$alphabet[0];
// loop to build all the JOINs
for($i=0; $i<count($compiled_url); $i++)
{
$sql_query .= " INNER JOIN tbl_pages ".$alphabet[$i+1]." ON ".$alphabet[$i+1].".page_id = ".$alphabet[$i].".page_parent";
}
// loop to build all the WHERE filters
$where = array();
for($i=0; $i<count($compiled_url); $i++)
{
$where[] = $alphabet[$i].".page_slug = '".$compiled_url[$i]."'";
}
$sql_query .= " WHERE ".implode(" AND ",$where);
// if results are found print "page found" else print "page not found"
if(mysqli_num_rows($url_results) > 0)
{
echo "page found <br>";
$result = mysqli_fetch_array($url_results);
$compiled_parent=$result['page_id'];
}
else
{
echo "page not found <br>";
break;
}
The problem with your code, that you have to check outside of the for loop not inside it. And I think you added some wrong data in your database.
So consider your table looks like this
tbl_pages
page_id | page_slug | page_parent
--------+-----------+------------
1 | posts | 0
2 | daily | 1 // <-- edited from 2 to 1
Then you use this script
$compiled_url = explode("/",$compiled_url);
$parent = 0;
$correct = true;
foreach($compiled_url as $item){
$results = mysqli_query($webapp_db,
"SELECT * FROM tbl_pages WHERE page_slug='" . $item . "' AND page_parent ='" . $parent . "' LIMIT 1"
);
if($row = mysqli_fetch_array($result)){
$parent = $row['id'];
} else {
$correct = false;
break;
}
}
if($correct){
echo "page found <br>";
} else {
echo "page not found <br>";
}
Edit this code as you wish and be aware of sql injections if you use it as is.

PHP List Menu Boxes - Best way to do the cycle?

This is part of code from my backoffice page. ( is an edit.php page for a user to edit / modify )
// first query to get cats from user table
$query = "select * from user where name='".$_SESSION['username']."' order by id ASC limit 1";
$result=mysql_query($query);
if (mysql_num_rows($result)) {
while($row=mysql_fetch_array($result)){
$cat1 = $row['cat1'];
$cat2 = $row['cat2'];
$cat3 = $row['cat3'];
$cat4 = $row['cat4'];
$cat5 = $row['cat5'];
$cat6 = $row['cat6'];
$cat7 = $row['cat7'];
$cat8 = $row['cat8'];
$cat9 = $row['cat9'];
$cat10 = $row['cat10'];
}
}
// now i want to build 10 select boxes with selected according the user table $cats
// below is what i can build to first box $cat1
// is there a way i can produce this for the 10 select boxes whitout having to make 10 cycles of bellow code
<select name="theme" id="theme">
<?php
$q1 = 'SELECT * FROM cats ORDER BY title ASC';
$r1 = mysql_query($q1);
while( $row = mysql_fetch_array($r1)) {
if ( $cat1 == $row['id'] ) {
print "<option class=\"cssoption\" selected=\"selected\" value=\"".$row['id']."\">".htmlentities($row['title'])."</option>";
}
else {
print "<option class=\"cssoption\" value=\"".$row['id']."\">".htmlentities($row['title'])."</option>";
}
}
?>
</select>
I am not a coder so this might not be effective code.
Hope someone can help me here and understands what i am trying to do.
Many Thanks.
The code is fine. This 10 cycles as you name it is a almost zero cost.
This is the usual way we do it, we fetch sequentialy the records one by one.
In addition it makes no sense to ask not to do the 10 cycles because you are applying an if else condition in the same time, this means that you check every record if the cat id is the same with the row so you need the loop.
On the other hand if for some reason you want to skip some records, you can use the mysql seek function to start fetching from the desired record.
for($i=0;$i<99999;$i++)
(9999*9999);
echo 'This time the cost of this loop was:',(microtime()-$start),' seconds.';
?>

Associate different data

I will try to be as clear as possible because I can't get anybody to help me around,
I am trying to associate some data from a 'videos' table with their respective ID.
Lets say, I have column ID, title, serie, season, episode.
I am getting my data :
<?
$result = mysql_query("SELECT * FROM videos WHERE serie = '".$row['serie']."' AND season = '".$row['season']."'");
$total_rows = mysql_num_rows($result);
?>
(that is in the page where you see the video itself)
So now I can get the number of episodes from a serie and season.
What I'm trying to do is have a link for the next episode, and aa link for the previous one. In the URL I am working with the id, so http://website.com/view/id/'video id here'/
So how can I get the ID of the following and previous episodes of the same season AND serie?
Help will be much appreciated!
The easiest thing I thought of is
<?=$row['id'] + 1?>
<?=$row['id'] - 1?>
But the thing is that it's mixed videos, so it wont work 100%
I think you've taken my example too literally. I'll post a complete example in the morning (I'm just replying from my iPhone at the mo). For some reason it wouldn't let me add a comment to your last reply, so sorry this is as an answer.
[edit] here's a more complete example:
<?php
$result = mysql_query("SELECT * FROM videos WHERE series='$series' AND season = '$season'");
$last_row = null;
$next_row = null;
$current_id = $_GET['id'];
while($row = mysql_fetch_assoc($result)) {
if($current_id == $row['id']) {
$next_row = mysql_fetch_assoc($result);
break;
}
$last_row = $row;
}
if($last_row != null) {
echo "<a href='?id={$last_row['id']}'>Prev</><br/>\n";
}
if($next_row != null) {
echo "<a href='?id={$next_row['id']}'>Next</><br/>\n";
}
?>
A few things to note:
This is untested.
In your initial example, I didn't know where you were getting the $row['serie'] and $row['season'], so in my example, I've just used the variables $series and $season. You'll have to fill these in with what you want the current result set to be filtered by.
For my example, the URL format uses the GET layout (ie. ?id=).
If you do:
$results = mysql_query($sql);
(where $sql is your mentioned select statement)
Then the $results array will contain all results of that series/season.
So you can access it via:
$previous = $results[$n - 1];
$next = $results[$n + 1];
$previous_id = $previous['id'];
$next_id = $next['id'];
Note that you'll of course need to check that $n - 1 isn't less than zero, and ($n + 1) isn't greater than your $total_rows.
Here is what I tried, I guess it is what you meant,
All that it's doing is put the previous episode, so I get /view/id/3/ (if the episode i am watching is 4)
<?
$result = mysql_query("SELECT * FROM videos WHERE serie = '".$row['serie']."' AND season = '".$row['season']."'");
$total_rows = mysql_num_rows($result);
$previous = $results[$n - 1];
$next = $results[$n + 1];
$previous_id = $previous['id'];
$next_id = $next['id'];
?>
<? if($row['episode'] == 1) { ?>
<td align="center" width="33%"></td>
<? } else { ?>
<td align="center" width="33%"><img src="images/previous.gif" srcover="images/previoush.gif" alt="Previous Video" border="0" /></td><? } ?>
That is only for the previous one,
Sorry I had to post like this, if not it wouldnt have appeared correctly,
(Correct me if I'm wrong with the code)
And thanks for the reply

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