issues with php if statement within foreach loop - php

I did have a quick search on this but couldn't find anything relating to my problem. I'm having issues with an if statement within a foreach loop. I'm pulling a list of categories from one class, and a single category to be selected from another. The code below (with the if statement removed) works perfectly, and returns 12 options with populated values.
foreach ($user_info->categories as $key=>$category) {
$category_name = $user_info->category_names[$key];
echo '<option value="'.$category.'">'.$category_name.'</option>';
}
However when I add the if statement inside as below:
foreach ($user_info->categories as $key=>$category) {
$category_name = $user_info->category_names[$key];
if ($category = $get_article_info->category_1) {
echo '<option value="'.$category.'" selected="selected">'.$category_name.'</option>';
} else {
echo '<option value="'.$category.'">'.$category_name.'</option>';
}
}
I get a list of options with the text populated but all twelve options have value="". $get_article_info->category_1 works when echoed on it's own, and even if it were not found I would expect the if statement to echo 12 options without any selected (the same as the first code example).

You are using = instead of == You should change
if ($category = $get_article_info->category_1) {
To
if ($category == $get_article_info->category_1) {

Related

PHP foreach targeting specific item

I got a DB query that pulls out three items randomly from several categories. I want to show "Selected" if one of the items is from a specific category. Right now if one of the items is from that specific category the "Selected" is showing on all three items. How can I target the specific item only?
foreach ( $rows as $row ) {
if ($row->catid == 56) {
echo "Selected";
}
Your question isn't very clear, but I suspect you're trying to add the attribute to an option. You need to do this in the same loop that echoes the option.
foreach ($rows as $index => $row) {
$selected = $row->catid == 56 ? "SELECTED" : "";
$itemnum = $index + 1;
echo "Item $itemnum - Category $row->catid $selected | ";
}
foreach ( $rows as $row ) {
if ($row->catid == 56) {
echo "Selected";
break;
}
Not sure what u want accomplish but i guess u want to show only one selected so u need to break loop if item is found

For loop for two tables

if(count($search)==0) {
for($i=0;$i<count($about);$i++) {
$bd->insert("search","page_title,page_description,page_url,image_id","'About','{$about[$i]['image_title']}','http://religiousbrands.in/demo/about.php?search=".$about[$i]['id']."','{$about[$i]['uniq_id']}'");
}
} else {
for($i=0;$i<count($about);$i++) {
for($k=0,$j=0;$k<=$i,$j<count($search);$j++,$k++) {
if($search[$j]['image_id']==$about[$i]['uniq_id']) {
echo "update".$i.'and'.$k.'and'.$j;
echo"<br>";
$bd->update("search",
"page_title='About',page_description='{$about[$i]['image_title']}',page_url='http://religiousbrands.in/demo/about.php?search=".$about[$i]['id']."' ","image_id='{$about[$i]['uniq_id']}' limit 1");
}
}
}
}
$search is an array which I am getting from my database . first I m checking if the search table is empty or not . if empty then insert the values in the search table .
$about is also an array which i am getting from my database . if $search is not empty Then I am updating the value but checking first that $search[$j]['image_id']===$about[$i][uniq_id] and HERE IS MY PROBLEM START :
Suppose in my table about there are 3 entries ie :
uniq_id=1
uniq_id=2
uniq_id=3
and In my table search there are 2 entries ie:
image_id=1
image_id=2
So the search table is not empty So it will follow the 2nd condition. So i was trying that table $about[1]['uniq_id'] should check for $search[1]['image_id'] and $search[2]['image_id'] and etc $search[$i]['image_id'] if the table has any values
but I my for loop is not working like I want So anybody can help me in this
You'll need to know which rows in the "search" table need adding (INSERT) and which ones need updating.
Perhaps try looping through the "search" array first and find which "image_id" values you have.
$image_ids = array();
foreach ($search as $item) {
$image_ids[] = $item['image_id'];
}
Next, loop through the "about" array. Use the ID's in the "$image_ids" array to determine whether you need to UPDATE or INSERT an item.
foreach ($about as $item) {
if (in_array($item['image_id'], $image_ids)) {
// Item already exists. Update it.
} else {
// Item doesn't exist. Add it.
}
}
This is also much faster than putting loops inside loops.

stopping loops in php(break and continue not working for me)

I have some series of loops in my php for an example
//select statement
while (gyu_fetch($acaYear_results)) {
$Year = gyu_get_col($Year_results,0);
$page->main .= '<option value="'.$Year.'"';
if ($Year!="" and $Year==$Year) { $page->main .= ' selected="selected"'; }
$page->main .= '>'.$Year.'</option>';
}
//select statment
while(gyu_fetch($domain_results)) {
$row = gyu_get_col($results,0);
$page->main .= '<option value="'.$row.'">'.$row.'</option>';
}
if ($tui_domain != $tui_domain_old and $tui_domain_old != 'REiOl7')
{
$page->main .= '<tr><td colspan="4" style="background-color:#DDDDDD;"> </td></tr>';
}
In all my while loops and foreach loops I have used break; and continue; but when I used each of them in my select statements.
what happens is that my webpage will not render completely as it will only affect other if statements.
I was wondering if there are other ways to stop while or if statements from not looping over and over again but does not affect any element of the page that might be using it for example
while(gyu_fetch($domain_results)) {
$row = gyu_get_col($results,0);
break;
}
$page->main .='"'.$row.'"';
In that example although I have ends execution of the current while structure will this affect '"'.$row.'"' being used?
You cannot use $row outside the while loop as it is, since it is declared inside the loop and is thus local to it. Try initializing it before the loop ( $row=''; ).
More on variable scope in PHP

Adding commas to a loop within a loop

I'm trying to create a list using a loop within a loop. I have 3 tables.
T1: faculty
T2: keywords
T3: facID, keywordID
I've created a select statement to cross join the rows and spit out something like this:
Faculty Name A
keyword-a keyword-b keyword-c
Faculty Name B
keyword-a keyword-d keyword-f
Everything works great except I need to add commas to the keyword list and my code isn't doing the trick. My keywords are still looping through without the comma.
<?php while ($row = mysql_fetch_assoc($result)) { ?>
<?php if ($row['facID'] !== $lastID ) { ?>
<?php echo $row['facname']; ?><br />
<?php $lastID = $row['facID']; ?>
<?php } ?>
<?php $kwords = array();
foreach($row as $k => $v) {
if (strpos($k, 'kword') === 0) {
$kwords[] = $v;
}
}
echo implode(', ', $kwords);
} ?>
Any suggestions? I'm a noob and I'm hoping it's something very obvious!
There seem to be a few issues with your code, so I'll try to address them all.
First, you have a lot of opening and closing <?php> tags, and it's really messing with the readability of your code. Consider keeping as much code as possible contained into a single <?php> code block. For example, instead of this:
<?php if ($row['facID'] !== $lastID ) { ?>
<?php echo $row['facname']; ?><br />
<?php $lastID = $row['facID']; ?>
<?php } ?>
...you can consolidate all of that PHP code into this:
<?php
if ($row['facID'] !== $lastID ) {
echo $row['facname'] . "<br />";
$lastID = $row['facID'];
}
?>
Next, you're not outputting any sort of visual break after echoing out your implode()ed array. This would lead to the next heading being output on the same line as the output of your previous heading. For example, your first two headings will end up like this:
Faculty Name A
keyword-a keyword-b keyword-cFaculty Name B
keyword-a keyword-d keyword-f
Notice how Faculty Name B is at the end of the line of keywords?
Finally, I think the problem you're reporting is that you're getting two keywords that are linked together. For example, if you had two rows of data with the same facility id, one with keywords keyword-a and keyword-b and another with keyword-c and keyword-d, you would see that output visually without a comma between keyword-b and keyword-c.
In other words, instead of this:
keyword-a, keyword-b, keyword-c, keyword-d
...you're instead seeing this:
keyword-a, keyword-bkeyword-c, keyword-d
This is also caused by the lack of a visual break between implodeed lines, but I believe the problem is deeper than that. I believe you want all keywords for a given facility to be shown on a single line, not broken across multiple lines. For that, you need to move where you reinitialize your array so that it gets reinitialized at the same time you switch to a new heading. Try something like this:
$kwords = array();
while ($row = mysql_fetch_assoc($result)) {
if ($row['facID'] !== $lastID ) {
if ($kwords) {
echo implode(", ", $kwords) . "<br />";
$kwords = array();
}
echo $row['facname'] . "<br />";
$lastID = $row['facID'];
}
foreach($row as $k => $v) {
if (strpos($k, 'kword') === 0) {
$kwords[] = $v;
}
}
}
if ($kwords) {
echo implode(", ", $kwords);
}
echo "<br />";
This still isn't the best code, but you can refactor it.
The idea here is that the array gets output and reset every time the facility changes, so that the array encompasses all keywords for that facility and they all get output together, rather than being reported only as part of the database row they were returned with. After the loop completes, you have to manually report the last row since the usual reporting is taken care of within the loop.

When listing information from a database using php and mysql how would you make the first row look different to the rest?

Basically I have articles in my database and I want to alter the way the first record displays. I want the lastest (Posted) article to be the focus and the older article just to list, (see F1.com). I need to know how to get the first of my values in the array and get it to display differently but I am not sure how to do this, I can do it so all rows display the same just not how to alter the first row. I also need to know how to tell the rest of the rows to display the same afterwards im guessing you use an if statement there and before that some kind of count for the rows.
Current code:
$result = mysql_query("SELECT * FROM dbArticle WHERE userID='".$_SESSION["**"]."' ORDER BY timestamp DESC");
while($row = mysql_fetch_array($result))
{
echo "<h2 class=\"heading1\">". $row['title'] ."</h2>";
echo "By: ".$row['username']." Type: ".$row['type']." Posted: ".$row['timestamp']."
$body = $row['body'];
echo "<br/><p>";
echo substr("$body",0,260);
echo "...<span class=\"tool\"><a class=\"blue\" href=\"index.php?pageContent=readArticle&id=".$row['id']."\">Read More</a></span></p><hr/>";
}
mysql_close($con);
Ok I have taken Luke Dennis's code and tried to test it, but I am getting this error: Warning: Invalid argument supplied for foreach() this is the line of the foreach statment. Something that has just come to mind is that I will only want 5 or so of the older articles to display. This is what I have thats creating the error:
<? $con = mysql_connect("localhost","****","***");
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
mysql_select_db("******", $con);
$result = mysql_query("SELECT * FROM dbArticle ORDER BY timestamp DESC");
$first = true;
foreach($result as $row){
if($first)
{
echo"".$row['title']."";
echo"this is the headline";
$first = false;
}
else
{
echo"".$row['title']."";
}
}
?>
Do I need to add mysql_fetch_array somewhere to set the array up?
I would just iterate through the results and apply a css class to the first entry:
$first = true;
while ($row = mysql_fetch_assoc($result)) {
$cssClass = '';
if ($first) {
$cssClass = 'highlight';
}
echo '<p class="' . $cssClass . '">' . $row['text'] . '</p>';
$first = false;
}
It's a bit crude, but I often hard-code a variable to designate the first run through a loop. So something like:
$first = true;
foreach($list_of_items as $item)
{
if($first)
{
// Do some stuff
$first = false;
}
else
{
// Do some other stuff
}
}
A simple if statement when looping through your results will usually do the trick. You can use a boolean to indicate if you've output the first row of results or now. If you haven't then give it a particular style and then set the boolean to true. Then all subsequent rows get a different style.
All of the above are correct. Luke Dennis' post is of course fleshed-out a bit more.
As Brian Fisher said, add some CSS styling to the first link when you encounter it per Luke's post.
I took a look at the article list on the F1 website. Pretty well constructed site - "One would expect that." :-)
Anyway, the article listings are contained within a two row table (summary="Latest Headlines") in descending order (newest first).
Just place a class in the second column (<td class="first-news-article">). Then add the class name and appropriate styling values in the css file - probably your' modules.css. There's already quite a few class values associated with articles in that file, so you may be able to just use an existing value.
That should be about it - other than actually doing it!
By the way, judging by the quality of the underlying html, I'm assuming there's already an "article list emitter." Just find that emitter and place the appropriate conditional to test for the first record.
Darrell
I just noted your code addition. I assume that you were showing the F1 site as an example. Anyway, I think you're on your way.
I presume you have some code that loops through your resultset and prints them into the page? Could you paste this code in, and that might give us a starting point to help you.
I don't know PHP, so I'll pseudocode it in Perl. I wouldn't do it like this:
my $row_num = 0;
for my $row ($query->next) {
$row_num++;
if( $row_num == 1 ) {
...format the first row...
}
else {
...format everything else...
}
}
The if statement inside the loop unnecessarily clutters the loop logic. It's not a performance issue, it's a code readability and maintainability issue. That sort of thing just BEGS for a bug. Take advantage of the fact that it's the first thing in the array. It's two different things, do them in two different pieces of code.
my $first = $query->next;
...format $first...
for my $row ($query->next) {
...format the row...
}
Of course, you must make the first row stand out by using tags.
I'd use array_shift():
$result = mysql_fetch_assoc($resultFromSql); // <- edit
$first = array_shift($result);
echo '<h1>'.$first['title'].'</h1>';
foreach ($result as $row) {
echo '<h2>'.$row['title'].'</h2>';
}
The best way to do this is to put a fetch statement prior to the while loop.
Putting a test inside the while loop that is only true for one iteration can be a waste of time for a result of millions of rows.

Categories