Periods/loop added to foreach results

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
Wookie
Forum Newbie
Posts: 2
Joined: Fri Sep 26, 2008 9:33 am
Location: Sugar Land, TX
Contact:

Periods/loop added to foreach results

Post by Wookie »

Hey everyone,
I'm experiencing some weird results when I run a script inside a different PHP file as opposed to by itself.
PHP appears to adding a period (.) to each blank MySQL column run through the foreach - almost like it's getting the periods that are used to connect variables - and not clearing a variable, or something.

If I run the script by itself, it works fine:

Code: Select all

$query  = "SELECT * FROM sermons ORDER BY sermon_date DESC LIMIT 1";
$result = mysql_query($query);
 
while ($row = mysql_fetch_array($result)){
 
    $book1 = $row['sermon_scripture_book1'];
    $book1_verses = $row['sermon_scripture_book1_verses'];
    $book2 = $row['sermon_scripture_book2'];
    $book2_verses = $row['sermon_scripture_book2_verses'];
    $book3 = $row['sermon_scripture_book3'];
    $book3_verses = $row['sermon_scripture_book3_verses'];
    
    $booksandVerses = array (
        $book1 => $book1_verses,
        $book2 => $book2_verses,
        $book3 => $book3_verses
    );
    
    foreach ($booksandVerses as $key => $value){
        if ($key !== "" || $value !== ""){
        
            if ($key != ""){
                if ($scripture == ""){
                    $scripture = getBook($key, "abbr");
                } else {
                    $scripture .= ", " . getBook($key, "abbr");
                }
            }
        
            if ($value != ""){
                $scripture .= " " . $value;
            }
            
        }
        else {
            if ($scripture == ""){
                $scripture = "NA";
            }
        }
    
    }
 
}
 
echo $scripture;
Where data that looks like this:

Code: Select all

$booksandVerses = array (
    "44" => "21:17-39",
    "" => "",
    "" => ""
);
would return this:
Act. 21:17-39
and data like this:

Code: Select all

$booksandVerses = array (
    "44" => "10:1-12, 12:6-12",
    "22" => "2:14",
    "" => ""
);
would return this:
Act. 10:1-12, 12:6-12, Son. 2:14
(without the getBook function, defined elsewhere, it would be more like "44 10:1-12")

When I remove the "LIMIT 1" on the query, using the above document, it works great (no line breaks):
Act. 21:17-39, Psa. 77, Act. 21:1-16, Act. 20:13-38, Act. 20:1-12, Act. 19:21-41, Isa. 65:17, 2Pe. 3:13
But I stick the same code inside another document I get a loop like this:
Image
Notice the periods added where there are blank values, which did not appear in the first document. Not to mention how it's copying the previous while loop's value at the beginning of each row :?
I've tried unsetting variables and adding $scripture = ""; before the foreach unsuccessfully, among other things.

Of course, here is the code for the second document I'm referring to:

Code: Select all

<?php
#############################################################
$rowsPerPage = 30;
$pageNum = 1;
if(isset($_GET['page'])){ $pageNum = $_GET['page']; }
$offset = ($pageNum - 1) * $rowsPerPage;
############################################################
include './inc/db/config.php';
include './inc/db/opendb.php';
include './inc/functions.php';
############################################################
 
 
$query  = "SELECT * FROM sermons ORDER BY sermon_date DESC LIMIT $offset, $rowsPerPage";
$result = mysql_query($query);
 
 
while ($row = mysql_fetch_array($result)){
 
    $id = $row['sermon_id'];
    
    $date = dateFromMySQL($row['sermon_date']);
    $date_display = displayDate($date);
    
    $title = htmlspecialchars($row['sermon_title']);
    $speaker = $row['sermon_speaker'];
 
 
    //SERIES OR EVENT?
    
    if ($row['sermon_series'] !== "" && $row['sermon_event'] == "") {
        $seriesORevent = "series";
        $series = $row['sermon_series'];
    }
    elseif ($row['sermon_series'] == "" && $row['sermon_event'] !== "") {
        $seriesORevent = "event";
        $event = $row['sermon_event'];
    }
    
 
    $book1 = getBook($row['sermon_scripture_book1'], "abbr");
    $book1_verses = $row['sermon_scripture_book1_verses'];
    $book2 = getBook($row['sermon_scripture_book2'], "abbr");
    $book2_verses = $row['sermon_scripture_book2_verses'];
    $book3 = getBook($row['sermon_scripture_book3'], "abbr");
    $book3_verses = $row['sermon_scripture_book3_verses'];
    $scripture_other = $row["sermon_scripture_other"];
    
    $sermon_path = "/audio/sermons/";
    $sermon_filename = str_replace("/", "", $date) . ".wma"; // 062208.wma
    $notes_path = "/audio/notes/";
    $notes_filename = str_replace("/", "", $date) . ".pdf"; // 062208.pdf
 
 
 
    ############################################################
    
    //book
    //if ( is_numeric($book) && strlen($book) <= 4){
    //  $book = getBook($book,'abbr');
    //}
    
    //speaker
    if ( is_numeric($speaker) && strlen($speaker) <= 4){
        $speaker = getSpeaker($speaker, 'name');
    } elseif ($speaker == ""){
        $speaker = "NA";
    }
    
    //series OR event
    if ($seriesORevent == "series"){
        if ( is_numeric($series) && strlen($series) <= 4){
            $seriesEvent = getSeries($series);
        } elseif ($seriesEvent == ""){
            $seriesEvent = "NA";
        }
    }
    elseif ($seriesORevent == "event"){
        if ( is_numeric($event) && strlen($event) <= 4){
            $seriesEvent = getEvent($event);
        } elseif ($seriesEvent == ""){
            $seriesEvent = "NA";
        }
    }
    elseif ($seriesORevent == ""){
        $seriesEvent = "NA";
    }
    
    ############################################################
    
    
    $booksandVerses = array (
        $book1 => $book1_verses,
        $book2 => $book2_verses,
        $book3 => $book3_verses
    );
 
    
    foreach ($booksandVerses as $key => $value){
        if ($key !== "" || $value !== ""){
        
            if ($key != ""){
                if ($scripture == ""){
                    $scripture = getBook($key, "abbr");
                } else {
                    $scripture .= ", " . getBook($key, "abbr");
                }
            }
        
            
            if ($value != ""){
                $scripture .= " " . $value;
            }
            
        }
        else {
            if ($scripture == ""){
                $scripture = "NA";
            }
        }
    
    }
        
    
    // GENERATE DOWNLOAD LINK
    if (file_exists("./sermons/".$sermon_filename)){
        $sermon = '<a href="download.php?type=sermon&file='.$sermon_filename.'" title="Download"><img src="inc/gfx/download.gif" alt="Download" /></a>';
        $play = '<a href="javascript&#058;playSermon(\''.$id.'\');" title="Play Sermon"><img src="inc/gfx/play.gif" alt="Play" /></a>';
    }
    else {
        $sermon = "Download";
        $play = "Play";
    }
    
    // GENERATE NOTES LINK
    if (file_exists("./notes/".$notes_filename)){
        $notes = '<a href="download.php?type=notes&file='.$notes_filename.'" title="Notes"><img src="inc/gfx/notes.gif" alt="Notes" /></a>';
    }
    else {
        $notes = "Notes";
    }
    
    
    $sermons .= '<tr class="s '.$id.'" onmouseover="over(this);" onmouseout="out(this);" onclick="view(this,\''.$id.'\');">'.
            '<td>'.$date_display.'</td><td>'.$title.'</td><td>'.$scripture.'</td><td>'.$speaker.'</td><td>'.$seriesEvent.'</td>'.
        '</tr>'.
        "\n".
        '<tr class="collapse '.$id.'" style="display:none;">'.
            '<td class="con" colspan="5">'.
                '<table cellspacing="0">'.
                    '<tr>'.
                        '<td>'.$sermon.'</td>'.
                        '<td>'.$play.'</td>'.
                        '<td>'.$notes.'</td>'.
                    '</tr>'.
                '</table>'.
            '</td>'.
        '</tr>';
 
}
 
 
// how many rows we have in database
 
$query_countrows = "SELECT COUNT(sermon_id) AS numrows FROM sermons";
$result_countrows = mysql_query($query_countrows);
$countrows = mysql_fetch_array($result_countrows, MYSQL_ASSOC);
$numrows = $countrows['numrows'];
 
include './inc/db/closedb.php';
############################################################
$maxPage = ceil($numrows/$rowsPerPage);
$self = $_SERVER['PHP_SELF'];
 
if ($pageNum > 1)
{
    $page = $pageNum - 1;
    $prev = " <a href=\"$self?page=$page\">< Newer</a> ";
    $first = " <a href=\"$self?page=1\"><<</a> ";
} 
else
{
    $prev  = '< Newer ';
    $first = ' << ';
}
if ($pageNum < $maxPage)
{
    $page = $pageNum + 1;
    $next = " <a href=\"$self?page=$page\"> &nbsp;&nbsp;Older ></a> ";
    $last = " <a href=\"$self?page=$maxPage\">>></a> ";
} 
else
{
    $next = ' &nbsp;&nbsp;Older >';
    $last = ' >> ';
}
############################################################
 
$pagination = '<table class="pagenav" width="100%">'.
                    '<tr>'.
                        '<td class="l">'.$first.'</td>'.
                        '<td>'.$prev .'</td>'.
                        '<td class="c">Page <strong>'.$pageNum.'</strong> of <strong>'.$maxPage.'</strong></td>'.
                        '<td class="r">'. $next .'</td>'.
                        '<td class="r">'. $last .'</td>'.
                    '</tr>'.
                '</table>'.
                '<div style="font-size:83%;margin-bottom:30px;">'.$numrows.' sermons<br />Displaying '.$rowsPerPage.' per page</div>';
 
############################################################
?><!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" lang="en" xml:lang="en">
<head>
    <meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
    <title>Sermons</title>
</head>
<body>
 
<div align="center">
 
    
    <div style="width: 800px; text-align: left;">
 
        <table id="sermons" width="100%" cellpadding="0" cellspacing="0">
            <tr>
                <th width="70">Date</th>
                <th>Title</th>
                <th width="140">Scripture</th>
                <th width="110">Speaker</th>
                <th>Series / Event</th>
            </tr>
            <?php echo $sermons; ?>
        </table>
    
        <div align="center">
            <?php echo $pagination; ?>
        </div>
    
    </div>
</div>
 
</body>
</html>
I've been stuck on this for three weeks now, and I've googled my brains out, so I really appreciate any help you can give :D
Thanks!!
Wookie
Forum Newbie
Posts: 2
Joined: Fri Sep 26, 2008 9:33 am
Location: Sugar Land, TX
Contact:

Re: Periods/loop added to foreach results

Post by Wookie »

Okay then, I've figured it out. Sometimes you just need to take a break for a week to see everything in a new light. :roll:

I'm happy to share this script with anyone who could use it, so here's what I found out.

The problem with periods showing in the place of blank MySQL values was in fact the getBook() function I omitted from my previous post.
Below is that function, updated to fix the issue with an added if/then statement which omits the period if the value is blank:

Code: Select all

function getBook($id, $format){
    if ($format == "abbr"){
        $query_biblebook = "SELECT book_abbr FROM biblebooks WHERE book_id='$id'";
        $result_biblebook = mysql_query($query_biblebook);
        $row = mysql_fetch_array($result_biblebook);
            if ($row['book_abbr']){return $row['book_abbr'] . ".";}else{return "";}
    } elseif ($format == "name"){
        $query_biblebook = "SELECT book_name FROM biblebooks WHERE book_id='$id'";
        $result_biblebook = mysql_query($query_biblebook);
        $row = mysql_fetch_array($result_biblebook);    
            return $row['book_name'];
    }
}
In addition, to fix the variable not being cleared I added $scripture=""; on line 18 of the first code segment in my last post, before the foreach.

And that's that. Again, I appreciate this form and everyone who contributes.
If anyone wants more specifics about this script to make it functional (like database design, etc.) feel free to contact me.
Post Reply