headers already sent error (PHP)

ruud00000
ruud00000 used Ask the Experts™
on
What change(s) should I make to following PHP script in order for the 'headers already sent' error not to occur ?

Now the error occurs on calling header('Refresh: 3; url=#'); on line 300, stating :
Warning: Cannot modify header information - headers already sent by (output started at C:\xampp\htdocs\voetbaltoto\prognose.php:41) in C:\xampp\htdocs\voetbaltoto\prognose.php on line 300

The PHP Manual (http://nl.php.net/manual/en/function.header.php) point out:
'Remember that header() must be called before any actual output is sent, either by normal HTML tags, blank lines in a file, or from PHP. It is a very common error to read code with include, or require, functions, or another file access function, and have spaces or empty lines that are output before header() is called. The same problem exists when using a single PHP/HTML file.'

but I do not understand how exactly I would have to change my code in order to do that.
prognose.php
Comment
Watch Question

Do more with

Expert Office
EXPERT OFFICE® is a registered trademark of EXPERTS EXCHANGE®
Most Valuable Expert 2011
Top Expert 2016

Commented:
It is a law of HTTP that all headers must come first and be complete before any browser output can be sent (including invisible whitespace).  You might consider adding this instruction to the top of your script.

ob_start();

That will prevent the browser output until the script is finished.
Most Valuable Expert 2011
Top Expert 2016

Commented:
Hmm, as I look at the script, and admittedly I do not understand the comments, I am wondering what the purpose is for line 300?  Can you tell us in plain, non-technical language what this instruction is supposed to accomplish?

header('Refresh: 3; url=#');

Author

Commented:
The idea is following script from a PHP tutorial, where the 'header('Refresh: 3 url=#' line is supposed to refresh the page (therefore returning to the form) in case there where errors that need to be corrected. Proceeding to processing the values that where entered in the form should only be done after the input values where validated and correct.

<?php
include '../../inc/stats.php';
// Controle of een formulier gepost is
if($_SERVER['REQUEST_METHOD'] == 'POST')
{
    // Arrays declareren voor opslag van fouten en data
    $aErrors = array();
    $aData = array();
   
    // Velden die in het formulier aanwezig moeten zijn
    $aFormulierVelden = array('voornaam', 'achternaam');
   
    // Alle formuliervelden doorlopen
    foreach($aFormulierVelden as $sVeld)
    {
        // Controleren of er een waarde voor het formulierveld bestaat
        if(isset($_POST[$sVeld]))
        {    
            // Spaties aan begin en eind weghalen
            $sValue = trim($_POST[$sVeld]);
           
            // Controle of variabele gevuld is
            if(empty($sValue))
            {
                // Foutmelding toevoegen
                $aErrors[] = 'Je bent vergeten om '.$sVeld.' in te vullen';
            }
           
            // Ingevulde waarden aan data array toevoegen
            $aData[$sVeld] = $sValue;
        }
        else
        {
            $aErrors[] = 'Het veld '.$sVeld.' is niet gepost!';
        }
    }
   
    // Controleren of er geen fouten opgetreden zijn
    if(empty($aErrors))
    {
        // Formulier succes!
        echo '<p>Je hebt het formulier succesvol ingevuld! De volgende gegevens zijn bekend:</p>';
        echo '<p>Voornaam: '.$aData['voornaam'].'<br />';
        echo 'Achternaam: '.$aData['achternaam'].'</p>';
    }
    else
    {
        // Fouten opgetreden: weergeven en terug naar formulier
        header('Refresh: 3; url=formulier.php');
        foreach($aErrors as $sError)
        {
            echo '<p style="color:red">'.$sError.'</p>';
        }
    }
}
else
{
    // Verwerk.php mag nog niet bezocht worden, terug naar het formulier
    header('Location: formulier.php');
}
?>
Build an E-Commerce Site with Angular 5

Learn how to build an E-Commerce site with Angular 5, a JavaScript framework used by developers to build web, desktop, and mobile applications.

Author

Commented:
I tried adding ob_start(); but that doesn't seem to make a difference. Where exactly should the line be put?

Commented:
The most common cause of this is having a blank line or space at the start of a script.  Have you checked all involved scripts for that?
Most Valuable Expert 2011
Top Expert 2016
Commented:
Ahh... That makes sense, but it's a poor design pattern.  The professional solution for this kind of thing is to package the action script together with the form script, all in one PHP file.  Here is a teaching example of what I mean.
<?php // RAY_form_highlight_errors.php
error_reporting(E_ALL);


// DEMONSTRATE HOW TO HIGHLIGHT ERRORS IN FORM INPUT
// CLIENT IS ASKED TO PUT IN A VALUE
// IF THE VALUE FAILS OUR TEST WE SHOW AN ERROR MESSAGE
// WE PUT A MARKER NEXT TO THE INPUT CONTROL ON THE FORM
// WE TURN THE FORM BORDER RED
// SEE http://www.w3schools.com/CSS/pr_class_visibility.asp


// THESE CONDITIONS ARE SET FOR THE SCRIPT INITIALIZATION
$error_abc = 'hidden';
$boxer_abc = 'black';
$error_xyz = 'hidden';
$boxer_xyz = 'black';
$error_any = 'hidden';


// CAPTURE AND NORMALIZE THE POST VARIABLES - ADD YOUR OWN SANITY CHECKS HERE
$abc = (isset($_POST["abc"])) ? trim(strtoupper($_POST["abc"])) : NULL;
$xyz = (isset($_POST["xyz"])) ? trim(strtoupper($_POST["xyz"])) : NULL;

// IF ANYTHING WAS POSTED, VALIDATE IT
if (!empty($_POST))
{
    // VALIDATE THE 'abc' FIELD
    if ($abc != 'ABC')
    {
        $error_any = 'visible';
        $error_abc = 'visible';
        $boxer_abc = 'red';
        // $abc       = NULL;
    }

    // VALIDATE THE 'xyz' FIELD
    if ($xyz != 'XYZ')
    {
        $error_any = 'visible';
        $error_xyz = 'visible';
        $boxer_xyz = 'red';
        // $xyz       = NULL;
    }

    // DO WE HAVE INPUT FREE FROM ANY ERRORS?
    if ($error_any != 'visible')
    {
        echo "CONGRATULATIONS";
        die();
    }

    // OOPS - WE HAVE ERRORS
}

// IF NOTHING WAS POSTED, OR IF THERE ARE ERRORS, WE NEED NEW CLIENT INPUT
$form = <<<ENDFORM
<style type="text/css" media="all">
.error_any { visibility:$error_any; }
.error_abc { visibility:$error_abc; }
.error_xyz { visibility:$error_xyz; }
</style>
<pre>
<form method="post">
<span class="error_any">PLEASE CORRECT THE FOLLOWING ERRORS</span>
<span class="error_abc">YOU MUST ENTER 'abc' IN THIS FIELD</span>
PLEASE ENTER "ABC" HERE: <input style="border-color:$boxer_abc;" name="abc" value="$abc" />
<span class="error_xyz">YOU MUST ENTER 'xyz' IN THIS FIELD</span>
PLEASE ENTER "XYZ" HERE: <input style="border-color:$boxer_xyz;" name="xyz" value="$xyz" />
<input type="submit" />
</form>
ENDFORM;

// WRITE THE FORM WITH THE APPROPRIATE CSS STYLES ON THE ERROR MESSAGE FIELDS
echo $form;

Open in new window

Most Valuable Expert 2011
Top Expert 2016

Commented:
To YoderCM's comment, here is an example of a common error...
<?php $x = 3; ?>
<?php session_start(); // THIS INSTRUCTION FAILS

Open in new window

The reason for the failure is that the session handler uses cookies, cookies are part of the HTTP headers and the headers must precede the browser output.  But where is the browser output?  In this example, it is one "end-of-line" character, invisible whitespace that follows the first close-PHP tag and precedes the second start-PHP tag.  Hard to see, but there nonetheless!

Author

Commented:
Still don't understand...

To the above example: what would be the correct syntax then? Having both php instructions on one line?
<?php $x = 3; ?><?php session_start();

Furhermore, I have the form and the action together on one php page actually (as opposed to the tutorial example I provided) so that should be ok then?
Most Valuable Expert 2011
Top Expert 2016

Commented:
Please post the actual code you're using and I'll try to make some suggestions.

Regarding the little PHP script that fails because of invisible whitespace, the correct way is to eliminate the close/re-open sequence.  As a general rule, the better programmers will use the minimum number of start/stop sequences and the minimum number of echo statements.
<?php $x = 3;
session_start();

Open in new window

Commented:
Just move your session start FIRST:

<?php session_start();
$x = 3;

Author

Commented:
Here's the code (was attached to the original message).

So, following your last comment, I should not end the php script on line 5 (or anywhere else until the end of the file) but continue the whole script within that one 'start/stop sequence' echo-ing everything that is now outside the php tags?

<?php
session_start();
ini_set('display_errors', 'On');
error_reporting(E_ALL);
?>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN" "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">

<head>
      <meta http-equiv="Content-Type" content="text/html;charset=ISO-8859-1" />
      <title>Voetbaltoto 2010 - CCS</title>
      <link rel="stylesheet" href="opmaak.css" type="text/css"/>            
</head>
<body>

      <div class="paginakopbox">
            <div class="paginakopcenterbox">
                  <img style="float: left;" src="images/school_logo.gif" alt="paginakop" />
                        <p class="paginakoptekst">Voetbaltoto 2010</p>
            </div>
      </div>

      <div id="dummypaginacenterbox">
            
            <div id="navigatiekolom">
                  <ol>
                        <li><a href="index.php">Home</a></li>
                        <li><a href="ideeenbus.php">Idee&euml;nbus</a></li>
                        <li>Deelnemer</li>
                        <ol style="list-style-type: none;">
                              <li><a href="deelnemer_toevoegen.php">Toevoegen</a></li>
                              <li><a href="deelnemer_wijzigen.php">Wijzigen</a></li>
                              <li><a href="deelnemer_verwijderen.php">Verwijderen</a></li>
                        </ol>      
                        <li>Prognose</>
                        <ol>
                              <li><a href="prognose_wijzigen.php">Per stuk</a></li>
                        </ol>
                        <li><a href="wedstrijd.php">Wedstrijden</a></li>
                        <li><?php if (isset($_POST["submit"])) { ?> <a href="prognose_wijzigen.php">Terug</a>  <?php } ?></li>
                  </ol>
            </div>
            
            <!-- breedte in afwijking van css -->
            <div id="paginainhoudbox" style="width: 745px">
                  <h1>Prognose wijzigen</h1>
                  <?php
                  // lijstje met deelnemers en wedstrijden maken voor formulier picklist
                  // $deelnemer = addslashes($_POST["deelnemer"]);      

                  include("includes/verbinding.inc.php");

                  $sql = "SELECT deelnrId, voornaam, tv, achternaam, email FROM `deelnemer` ORDER BY achternaam";
                  $deelnemerkeuzelijst = mysql_query($sql);

                  $sql = "SELECT WedstrijdId, Dag, Datum, Tijd, Team1, Team2 FROM `wedstrijd` ORDER BY WedstrijdId";
                  $wedstrijdkeuzelijst = mysql_query($sql);
                  
                  $verbreken = mysql_close($verbinding);      
                  ?>

                  <?php
                      // echo '<pre>'.print_r($_POST, true).'</pre>';
                  ?>

                  <!-- Eerst deelnemer selecteren -->
                  <?php
                  if ($_SERVER['REQUEST_METHOD'] != 'POST') {
                  // echo 'test00';
                  
                  ?>      
                        <!-- invoerveldje laten zien voor selectie deelnemer -->
                        <form style="width: 625px; " method="post" action="#">  
                              <div style="width: 605px; padding-top: 15px;">
                                    <span style="float: left; width: 100px;">Deelnemer :</span>
                                    <select style="float: left; width: 200px;" name="deelnemer">
                                    <?php
                                    while ($row = mysql_fetch_row($deelnemerkeuzelijst) ) {
                                          echo '<option value="'.$row['0'].'">'.$row['1'];
                                          if ($row['2']!="") {echo ' '.$row['2'];}
                                          echo ' '.$row['3'].'</option>';
                                          }
                                    ?>
                                    </select>
                                    <input style="margin-left: 15px;" type="submit" value="Selecteer" name="selectie" />
                              </div>      
                        </form>      
                        <?php
                        }
                  elseif (!isset($_POST["save"])) {
                        // prognoses van deze deelnemer ophalen uit de database en in een array
                        // zetten voor verder verwerking
                        $deelnemer= addslashes($_POST["deelnemer"]);      
                        
                        include("includes/verbinding.inc.php");
                        $sql = "SELECT scores.WedstrijdId, ScoreId, Dag, Datum, Tijd, Team1, Team2, IF(ISNULL(Prognose1),\"\",Prognose1) AS Prognose1, IF(ISNULL(Prognose2),\"\",Prognose2) AS Prognose2
                        FROM `scores`
                        LEFT OUTER JOIN `wedstrijd`
                        ON wedstrijd.WedstrijdId=scores.WedstrijdId
                        WHERE DeelnrId=".$deelnemer."
                        ORDER BY scores.WedstrijdId";
                        $prognoses = mysql_query($sql);
                        
                        $verbreken = mysql_close($verbinding);      // Verbreken van de verbinding met de database
                        
                        $aPrognoses[] = array();
                        $_SESSION['aPrognoses'] = $aPrognoses;

                        $i = 0;
                        while ($row = mysql_fetch_row($prognoses) ) {
                              ++$i;
                              // echo gettype($row);
                            // echo '<pre>0:'.print_r($row).'</pre>';
                              //$aPrognoses[$row[1]] = array ();
                              $aPrognoses[$row[1]]['wedstrijdId'] = $row[0];
                              $aPrognoses[$row[1]]['dag'] = $row[2];
                              $aPrognoses[$row[1]]['datum'] = $row[3];
                              $aPrognoses[$row[1]]['tijd'] = $row[4];
                              $aPrognoses[$row[1]]['team1'] = $row[5];
                              $aPrognoses[$row[1]]['team2'] = $row[6];
                              $aPrognoses[$row[1]]['prognose1'] = $row[7];
                              $aPrognoses[$row[1]]['prognose2'] = $row[8];

                              }
                        // voor debuggen:
                        /*
                        echo '<pre>a:'.gettype($aPrognoses).'</pre>';
                      echo '<pre>0:'.print_r($aPrognoses).'</pre>';
                      echo '<pre>1:'.print_r($aPrognoses[961]).'</pre>';
                      echo '<pre>1:'.print_r($aPrognoses[962]).'</pre>';
                      */
                      
                      /* Opbouw array $aPrognoses:
                        Array ( [0] => Array ( )
                                    [961] => Array (
                                          [wedstrijdId] => 1
                                          [dag] => vrijdag
                                          [datum] => 2010-06-11
                                          [tijd] => 16:00:00
                                          [team1] => Zuid-Afrika
                                          [team2] => Mexico
                                          [prognose1] => 2
                                          [prognose2] => 2
                                          )
                                    [962] => Array (
                                          [wedstrijdId] => 2
                                          [dag] => vrijdag
                                          [datum] => 2010-06-11
                                          [ijd] => 20:30:00
                                          [team1] => Uruguay
                                          [team2] => Frankrijk
                                          [prognose1] => 1
                                          [prognose2] => 1 )
                                    [963] => Array (
                                          etc      
                        waarbij 961 de waarde van veld ScoreId is van de prognose                  */
                        
                        // tabel met invoervelden laten zien
                        echo
                        '
                        <form style="width: 730px; " method="post" action="#">  
                        <table width="725px" border="0" cellpadding="0" cellspacing="0" style="background: #ECF6FF;">
                              <tr>
                                    <td colspan="2">&nbsp;&nbsp;Datum</td><td colspan="2">&nbsp;&nbsp;Wedstrijd</td><td colspan="2">&nbsp;&nbsp;Prognose</td>
                              </tr>
                        '
                        ;
                        
                        $even = true;            
                        foreach($aPrognoses as $iScoreId => $aPrognose) {
                               if ($iScoreId > 0) {
                                    if (!$even) { $even=true; echo '<tr class="alternate" style="font-weight: normal;">'; }
                                    else { $even=false; echo '<tr style="font-weight: normal;">'; }
                                    echo '<td>&nbsp;&nbsp;'.$aPrognose['dag'].'</td><td>&nbsp;&nbsp;'.$aPrognose['datum'].'</td><td>&nbsp;&nbsp;'.$aPrognose['team1'].'</td><td>&nbsp;&nbsp;'.$aPrognose['team2'].'</td>';
                                    echo '<td>&nbsp;&nbsp;<input type="text" size="2" name="prognose1[]" value="'.$aPrognose['prognose1'].'" /></td>';
                                    echo '<td>-&nbsp;&nbsp;<input type="text" size="2" name="prognose2[]" value="'.$aPrognose['prognose2'].'" />';
                                    echo '<input type="hidden" id="scoreId" name="scoreId[]" value="'.$iScoreId.'" />';
                                    echo '<input type="hidden" id="wedstrijdId" name="wedstrijdId[]" value="'.$aPrognose['wedstrijdId'].'" /></td>';
                                    echo '</tr>';
                                    }
                              }
                        unset($iScoreId);
                        
            
                        // einde tabel      
                        echo
                        '
                        </table>
                        <br />
                        <div style="text-align: center;">
                              <input type="submit" value="Opslaan" name="save" />
                        </div>
                        </form>
                        ';
                        }
                  
                  
                        
                  // formulier afhandelen met php:
                  if (isset($_POST["save"])) {
                         // voor debuggen:
                         /*
                        echo '<pre>5:'.gettype($_POST['prognose1']).'</pre>';
                        echo '<pre>6:'.gettype($_POST['prognose2']).'</pre>';
                        echo '<pre>6:'.gettype($_POST['scoreId']).'</pre>';
                      echo '<pre>7:'.print_r($_POST['prognose1']).'</pre>';
                      echo '<pre>8:'.print_r($_POST['prognose2']).'</pre>';
                      echo '<pre>8:'.print_r($_POST['scoreId']).'</pre>';
                        echo '<pre>9:'.gettype($_SESSION['aPrognoses']).'</pre>';
                        // echo '<pre>10:'.gettype($aPrognose).'</pre>';
                        */
                         
                      // Arrays declareren voor opslag van fouten en data
                      $aErrors = array();
                      $aData = array();
                      
                      // Alle formuliervelden doorlopen
                      $i = 0;
                      $j = 0;
                        foreach($_POST['prognose1'] as $sProg1) {
                               // echo $i.': '.$sProg1.' - type: '.gettype($sProg1).' - leeg: '.empty($sProg1).' - set: '.isset($sProg1).'<br />' ; // let op: de invoervelden zijn type string
                               $sProg1 = trim($sProg1);
                              $sProg2 = trim($_POST['prognose2'][$i]);
                               if ((empty($sProg1) and $sProg1 != "0") or (empty($sProg2) and $sProg2 != "0")) {
                                    if (empty($aErrors)) {
                                          $aErrors[$j] = 'Je hebt de prognose van wedstrijd '.$_POST['wedstrijdId'][$i];      
                                          }
                                    else {
                                          $aErrors[$j] .= ', '.$_POST['wedstrijdId'][$i];
                                          }
                                    }
                              $i++;
                              }
                        if (!empty($aErrors)) {
                              $aErrors[$j] .= ' niet (volledig) ingevuld';;
                              }
                         
                      // echo '<pre>11:'.print_r($aErrors).'</pre>';
                      
                     // Controleren of er geen fouten opgetreden zijn
                      if(empty($aErrors))
                      {
                          // Formulier succes!
                          echo '<p>Je ontvangt ter bevestiging een e-mail met de door jou ingevulde scores. Bewaar deze e-mail totdat de competitie voorbij is, als  reservekopie.</p>';
                          $gebruikersnaam = 'testgebruiker';
                          $voornaam = 'Jan';
                          $tv = 'van';
                          $spatie_tv = ' '.$tv;
                          $achternaam = 'Vooren';
                          $from = 'ruud@naastepad.net';
                          
                              // multiple recipients
                              $mailto = 'rbj.naastepad@schaersvoorde.nl';
                              $to = $voornaam.$spatie_tv.' '.$achternaam.' <'.$mailto.'>';
                              $bcc = 'info@computerhuys.nl';
                              
                              // subject
                              $subject = 'Prognoses ontvangen van '.$gebruikersnaam;
                              
                              // message
                              $message = '
                              <html>
                              <head>
                                <title>Prognoses ontvangen van '.$gebruikersnaam.'</title>
                              </head>
                              <body>
                                <p>De volgende prognoses werden van '.$gebruikersnaam.' ontvangen op '.date('d-m-Y').' om '.date('H:i').' uur:</p>
                                <table>
                                  <tr>
                                    <th>Person</th><th>Day</th><th>Month</th><th>Year</th>
                                  </tr>
                                  <tr>
                                    <td>Joe</td><td>3rd</td><td>August</td><td>1970</td>
                                  </tr>
                                  <tr>
                                    <td>Sally</td><td>17th</td><td>August</td><td>1973</td>
                                  </tr>
                                </table>
                              </body>
                              </html>
                              ';
                              
                              // To send HTML mail, the Content-type header must be set
                              $headers  = 'MIME-Version: 1.0' . "\r\n";
                              $headers .= 'Content-type: text/html; charset=iso-8859-1' . "\r\n";
                              
                              // Additional headers
                              $headers .= 'To: '.$to. "\r\n";
                              $headers .= 'From: Voetbaltoto Schaersvoorde 2012 <'.$from.'>' . "\r\n";
                              $headers .= 'Bcc: '.$bcc. "\r\n";
                              
                              // Mail it
                              mail($to, $subject, $message, $headers);
                      }
                      else
                      {
                          // Fouten opgetreden: weergeven en terug naar formulier
                          // zie ook: http://en.wikipedia.org/wiki/HTTP_refresh
                          header('Refresh: 3; url=#');
                          foreach($aErrors as $sError)
                          {
                              echo '<p style="color:red">'.$sError.'</p>';
                          }
                      }
                      
                        }  // einde isset post save
                      
                //}
             
                  // Verbinding met de database maken
                  // include("includes/verbinding.inc.php");

                  
                  ?>      
                        
            </div>
      </div>
      
      <div id="footer" class="footerbox">
            <div class="footercenterbox">

                   <a href="index.php">Home</a>
                   &nbsp;&nbsp;<a href="ideeenbus.php">Idee&euml;nbus</a>
                   &nbsp;&nbsp;<a href="deelnemer_toevoegen.php">Dn toev</a>
                   &nbsp;&nbsp;<a href="deelnemer_wijzigen.php">Dn wijz</a>
                   &nbsp;&nbsp;<a href="deelnemer_verwijderen.php">Dn verw</a>
                   &nbsp;&nbsp;<a href="prognose_wijzigen.php">Pr pstk</a>
                   &nbsp;&nbsp;<a href="wedstrijd.php">Wedstrijden</a>
                   <?php if (isset($_POST["submit"])) { ?> &nbsp;&nbsp;<a href="prognose_wijzigen.php">Terug</a>  <?php } ?>
                   <br />
                   <p>
                        <a href="http://validator.w3.org/check?uri=referer"><img
                              src="http://www.w3.org/Icons/valid-xhtml11"
                              alt="Valid XHTML 1.1" height="31" width="88" /></a>
                   </p>
                  
                  
            </div>
      </div>
</body>
</html>

Commented:
Remove the blank line:

<?php
session_start();
ini_set('display_errors', 'On');
error_reporting(E_ALL);
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN" "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
Most Valuable Expert 2011
Top Expert 2016

Commented:
The script needs a complete rewrite - reorganized with the action script at the top and the error handling integrated into the action script.  I think if it were my issue, I would hire  a professional programmer to rewrite it.  But maybe we can make some progress without starting over.  Here is a code segment near the end of the script:
// Fouten opgetreden: weergeven en terug naar formulier
// zie ook: http://en.wikipedia.org/wiki/HTTP_refresh
header('Refresh: 3; url=#');
foreach($aErrors as $sError)
{
    echo '<p style="color:red">'.$sError.'</p>';
}

Open in new window

And here is what you might try instead (substituting your own values for the URL).  Please be aware that this is not professional advice, but is a workaround.
// Fouten opgetreden: weergeven en terug naar formulier
foreach($aErrors as $sError)
{
    echo '<p style="color:red">'.$sError.'</p>';
}
// http://en.wikipedia.org/wiki/Meta_refresh
echo '<meta http-equiv="refresh" content="5; url=http://URL/">';

Open in new window

HTH, ~Ray

Author

Commented:
Thanks again. If it is not impossible to explain (isn't evaluating a form supposed to be pretty basic php stuff?) how it should be done I would be happy to follow the instructions (rewriting the whole code if I have to).

Here's what I can do bringing the number of php start-stop sessions down to one (in answer to your previous comment) but in that case get the same error after closing the first echo statement, on line 43, so indeed apparently the whole code structure is bad.

Can you explain with a few lines of code what would need to be set up differently?

By the way the workaround works indeed but I would rather learn how to do it properly (being eager to learn PHP...)

<?php
session_start();
ini_set('display_errors', 'On');
error_reporting(E_ALL);

echo
'
<?xml version=\"1.0\" encoding=\"ISO-8859-1\"?>\n
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN" "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">

<head>
      <meta http-equiv="Content-Type" content="text/html;charset=ISO-8859-1" />
      <title>Voetbaltoto 2010 - CCS</title>
      <link rel="stylesheet" href="opmaak.css" type="text/css"/>            
</head>
<body>

      <div class="paginakopbox">
            <div class="paginakopcenterbox">
                  <img style="float: left;" src="images/school_logo.gif" alt="paginakop" />
                        <p class="paginakoptekst">Voetbaltoto 2010</p>
            </div>
      </div>

      <div id="dummypaginacenterbox">
            
            <div id="navigatiekolom">
                  <ol>
                        <li><a href="index.php">Home</a></li>
                        <li><a href="ideeenbus.php">Idee&euml;nbus</a></li>
                        <li>Deelnemer</li>
                        <ol style="list-style-type: none;">
                              <li><a href="deelnemer_toevoegen.php">Toevoegen</a></li>
                              <li><a href="deelnemer_wijzigen.php">Wijzigen</a></li>
                              <li><a href="deelnemer_verwijderen.php">Verwijderen</a></li>
                        </ol>      
                        <li>Prognose</>
                        <ol>
                              <li><a href="prognose_wijzigen.php">Per stuk</a></li>
                        </ol>
                        <li><a href="wedstrijd.php">Wedstrijden</a></li>
                        <li>';
                        if (isset($_POST["submit"])) {
                        echo '<a href="prognose_wijzigen.php">Terug</a>  ';
                              }
                        echo '</li>
                  </ol>
            </div>
            
            <!-- breedte in afwijking van css -->
            <div id="paginainhoudbox" style="width: 745px">
                  <h1>Prognose wijzigen</h1>
                  ';
                  // lijstje met deelnemers en wedstrijden maken voor formulier picklist
                  // $deelnemer = addslashes($_POST["deelnemer"]);      

                  include("includes/verbinding.inc.php");

                  $sql = "SELECT deelnrId, voornaam, tv, achternaam, email FROM `deelnemer` ORDER BY achternaam";
                  $deelnemerkeuzelijst = mysql_query($sql);

                  $sql = "SELECT WedstrijdId, Dag, Datum, Tijd, Team1, Team2 FROM `wedstrijd` ORDER BY WedstrijdId";
                  $wedstrijdkeuzelijst = mysql_query($sql);
                  
                  $verbreken = mysql_close($verbinding);      

                // echo '<pre>'.print_r($_POST, true).'</pre>';

                  // Eerst deelnemer selecteren
                  if ($_SERVER['REQUEST_METHOD'] != 'POST') {
                  // echo 'test00';
                  
                        // invoerveldje laten zien voor selectie deelnemer
                        echo '
                        <form style="width: 625px; " method="post" action="#">  
                              <div style="width: 605px; padding-top: 15px;">
                                    <span style="float: left; width: 100px;">Deelnemer :</span>
                                    <select style="float: left; width: 200px;" name="deelnemer">';
                                    while ($row = mysql_fetch_row($deelnemerkeuzelijst) ) {
                                          echo '<option value="'.$row['0'].'">'.$row['1'];
                                          if ($row['2']!="") {echo ' '.$row['2'];}
                                          echo ' '.$row['3'].'</option>';
                                          }
                                    echo '
                                    </select>
                                    <input style="margin-left: 15px;" type="submit" value="Selecteer" name="selectie" />
                              </div>      
                        </form>';
                        
                        }
                  elseif (!isset($_POST["save"])) {
                        // prognoses van deze deelnemer ophalen uit de database en in een array
                        // zetten voor verder verwerking
                        $deelnemer= addslashes($_POST["deelnemer"]);      
                        
                        include("includes/verbinding.inc.php");
                        $sql = "SELECT scores.WedstrijdId, ScoreId, Dag, Datum, Tijd, Team1, Team2, IF(ISNULL(Prognose1),\"\",Prognose1) AS Prognose1, IF(ISNULL(Prognose2),\"\",Prognose2) AS Prognose2
                        FROM `scores`
                        LEFT OUTER JOIN `wedstrijd`
                        ON wedstrijd.WedstrijdId=scores.WedstrijdId
                        WHERE DeelnrId=".$deelnemer."
                        ORDER BY scores.WedstrijdId";
                        $prognoses = mysql_query($sql);
                        
                        $verbreken = mysql_close($verbinding);      // Verbreken van de verbinding met de database
                        
                        $aPrognoses[] = array();
                        $_SESSION['aPrognoses'] = $aPrognoses;

                        $i = 0;
                        while ($row = mysql_fetch_row($prognoses) ) {
                              ++$i;
                              // echo gettype($row);
                            // echo '<pre>0:'.print_r($row).'</pre>';
                              //$aPrognoses[$row[1]] = array ();
                              $aPrognoses[$row[1]]['wedstrijdId'] = $row[0];
                              $aPrognoses[$row[1]]['dag'] = $row[2];
                              $aPrognoses[$row[1]]['datum'] = $row[3];
                              $aPrognoses[$row[1]]['tijd'] = $row[4];
                              $aPrognoses[$row[1]]['team1'] = $row[5];
                              $aPrognoses[$row[1]]['team2'] = $row[6];
                              $aPrognoses[$row[1]]['prognose1'] = $row[7];
                              $aPrognoses[$row[1]]['prognose2'] = $row[8];

                              }
                        // voor debuggen:
                        /*
                        echo '<pre>a:'.gettype($aPrognoses).'</pre>';
                      echo '<pre>0:'.print_r($aPrognoses).'</pre>';
                      echo '<pre>1:'.print_r($aPrognoses[961]).'</pre>';
                      echo '<pre>1:'.print_r($aPrognoses[962]).'</pre>';
                      */
                      
                      /* Opbouw array $aPrognoses:
                        Array ( [0] => Array ( )
                                    [961] => Array (
                                          [wedstrijdId] => 1
                                          [dag] => vrijdag
                                          [datum] => 2010-06-11
                                          [tijd] => 16:00:00
                                          [team1] => Zuid-Afrika
                                          [team2] => Mexico
                                          [prognose1] => 2
                                          [prognose2] => 2
                                          )
                                    [962] => Array (
                                          [wedstrijdId] => 2
                                          [dag] => vrijdag
                                          [datum] => 2010-06-11
                                          [ijd] => 20:30:00
                                          [team1] => Uruguay
                                          [team2] => Frankrijk
                                          [prognose1] => 1
                                          [prognose2] => 1 )
                                    [963] => Array (
                                          etc      
                        waarbij 961 de waarde van veld ScoreId is van de prognose                  */
                        
                        // tabel met invoervelden laten zien
                        echo
                        '
                        <form style="width: 730px; " method="post" action="#">  
                        <table width="725px" border="0" cellpadding="0" cellspacing="0" style="background: #ECF6FF;">
                              <tr>
                                    <td colspan="2">&nbsp;&nbsp;Datum</td><td colspan="2">&nbsp;&nbsp;Wedstrijd</td><td colspan="2">&nbsp;&nbsp;Prognose</td>
                              </tr>
                        '
                        ;
                        
                        $even = true;            
                        foreach($aPrognoses as $iScoreId => $aPrognose) {
                               if ($iScoreId > 0) {
                                    if (!$even) { $even=true; echo '<tr class="alternate" style="font-weight: normal;">'; }
                                    else { $even=false; echo '<tr style="font-weight: normal;">'; }
                                    echo '<td>&nbsp;&nbsp;'.$aPrognose['dag'].'</td><td>&nbsp;&nbsp;'.$aPrognose['datum'].'</td><td>&nbsp;&nbsp;'.$aPrognose['team1'].'</td><td>&nbsp;&nbsp;'.$aPrognose['team2'].'</td>';
                                    echo '<td>&nbsp;&nbsp;<input type="text" size="2" name="prognose1[]" value="'.$aPrognose['prognose1'].'" /></td>';
                                    echo '<td>-&nbsp;&nbsp;<input type="text" size="2" name="prognose2[]" value="'.$aPrognose['prognose2'].'" />';
                                    echo '<input type="hidden" id="scoreId" name="scoreId[]" value="'.$iScoreId.'" />';
                                    echo '<input type="hidden" id="wedstrijdId" name="wedstrijdId[]" value="'.$aPrognose['wedstrijdId'].'" /></td>';
                                    echo '</tr>';
                                    }
                              }
                        unset($iScoreId);
                        
            
                        // einde tabel      
                        echo
                        '
                        </table>
                        <br />
                        <div style="text-align: center;">
                              <input type="submit" value="Opslaan" name="save" />
                        </div>
                        </form>
                        ';
                        }
                  
                  
                        
                  // formulier afhandelen met php:
                  if (isset($_POST["save"])) {
                         // voor debuggen:
                         /*
                        echo '<pre>5:'.gettype($_POST['prognose1']).'</pre>';
                        echo '<pre>6:'.gettype($_POST['prognose2']).'</pre>';
                        echo '<pre>6:'.gettype($_POST['scoreId']).'</pre>';
                      echo '<pre>7:'.print_r($_POST['prognose1']).'</pre>';
                      echo '<pre>8:'.print_r($_POST['prognose2']).'</pre>';
                      echo '<pre>8:'.print_r($_POST['scoreId']).'</pre>';
                        echo '<pre>9:'.gettype($_SESSION['aPrognoses']).'</pre>';
                        // echo '<pre>10:'.gettype($aPrognose).'</pre>';
                        */
                         
                      // Arrays declareren voor opslag van fouten en data
                      $aErrors = array();
                      $aData = array();
                      
                      // Alle formuliervelden doorlopen
                      $i = 0;
                      $j = 0;
                        foreach($_POST['prognose1'] as $sProg1) {
                               // echo $i.': '.$sProg1.' - type: '.gettype($sProg1).' - leeg: '.empty($sProg1).' - set: '.isset($sProg1).'<br />' ; // let op: de invoervelden zijn type string
                               $sProg1 = trim($sProg1);
                              $sProg2 = trim($_POST['prognose2'][$i]);
                               if ((empty($sProg1) and $sProg1 != "0") or (empty($sProg2) and $sProg2 != "0")) {
                                    if (empty($aErrors)) {
                                          $aErrors[$j] = 'Je hebt de prognose van wedstrijd '.$_POST['wedstrijdId'][$i];      
                                          }
                                    else {
                                          $aErrors[$j] .= ', '.$_POST['wedstrijdId'][$i];
                                          }
                                    }
                              $i++;
                              }
                        if (!empty($aErrors)) {
                              $aErrors[$j] .= ' niet (volledig) ingevuld';;
                              }
                         
                      // echo '<pre>11:'.print_r($aErrors).'</pre>';
                      
                     // Controleren of er geen fouten opgetreden zijn
                      if(empty($aErrors))
                      {
                          // Formulier succes!
                          echo '<p>Je ontvangt ter bevestiging een e-mail met de door jou ingevulde scores. Bewaar deze e-mail totdat de competitie voorbij is, als  reservekopie.</p>';
                          $gebruikersnaam = 'testgebruiker';
                          $voornaam = 'Jan';
                          $tv = 'van';
                          $spatie_tv = ' '.$tv;
                          $achternaam = 'Vooren';
                          $from = 'ruud@naastepad.net';
                          
                              // multiple recipients
                              $mailto = 'rbj.naastepad@schaersvoorde.nl';
                              $to = $voornaam.$spatie_tv.' '.$achternaam.' <'.$mailto.'>';
                              $bcc = 'info@computerhuys.nl';
                              
                              // subject
                              $subject = 'Prognoses ontvangen van '.$gebruikersnaam;
                              
                              // message
                              $message = '
                              <html>
                              <head>
                                <title>Prognoses ontvangen van '.$gebruikersnaam.'</title>
                              </head>
                              <body>
                                <p>De volgende prognoses werden van '.$gebruikersnaam.' ontvangen op '.date('d-m-Y').' om '.date('H:i').' uur:</p>
                                <table>
                                  <tr>
                                    <th>Person</th><th>Day</th><th>Month</th><th>Year</th>
                                  </tr>
                                  <tr>
                                    <td>Joe</td><td>3rd</td><td>August</td><td>1970</td>
                                  </tr>
                                  <tr>
                                    <td>Sally</td><td>17th</td><td>August</td><td>1973</td>
                                  </tr>
                                </table>
                              </body>
                              </html>
                              ';
                              
                              // To send HTML mail, the Content-type header must be set
                              $headers  = 'MIME-Version: 1.0' . "\r\n";
                              $headers .= 'Content-type: text/html; charset=iso-8859-1' . "\r\n";
                              
                              // Additional headers
                              $headers .= 'To: '.$to. "\r\n";
                              $headers .= 'From: Voetbaltoto Schaersvoorde 2012 <'.$from.'>' . "\r\n";
                              $headers .= 'Bcc: '.$bcc. "\r\n";
                              
                              // Mail it
                              mail($to, $subject, $message, $headers);
                      }
                      else
                      {
                          // Fouten opgetreden: weergeven en terug naar formulier
                          // zie ook: http://en.wikipedia.org/wiki/HTTP_refresh
                          header('Refresh: 5;');
                          // echo '<meta http-equiv="refresh" content="5; ">';

                          foreach($aErrors as $sError)
                          {
                              echo '<p style="color:red">'.$sError.'</p>';
                          }
                      }
                      
                        }  // einde isset post save
                      
                //}
             
                  // Verbinding met de database maken
                  // include("includes/verbinding.inc.php");

                  
                  echo
                  '
            </div>
      </div>
      
      <div id="footer" class="footerbox">
            <div class="footercenterbox">

                   <a href="index.php">Home</a>
                   &nbsp;&nbsp;<a href="ideeenbus.php">Idee&euml;nbus</a>
                   &nbsp;&nbsp;<a href="deelnemer_toevoegen.php">Dn toev</a>
                   &nbsp;&nbsp;<a href="deelnemer_wijzigen.php">Dn wijz</a>
                   &nbsp;&nbsp;<a href="deelnemer_verwijderen.php">Dn verw</a>
                   &nbsp;&nbsp;<a href="prognose_wijzigen.php">Pr pstk</a>
                   &nbsp;&nbsp;<a href="wedstrijd.php">Wedstrijden</a>
                   <?php if (isset($_POST["submit"])) { ?> &nbsp;&nbsp;<a href="prognose_wijzigen.php">Terug</a>  <?php } ?>
                   <br />
                   <p>
                        <a href="http://validator.w3.org/check?uri=referer"><img
                              src="http://www.w3.org/Icons/valid-xhtml11"
                              alt="Valid XHTML 1.1" height="31" width="88" /></a>
                   </p>
                  
                  
            </div>
      </div>
</body>
</html>';
Most Valuable Expert 2011
Top Expert 2016

Commented:
Check the post at ID: 37850700 for an overview of the general way I approach these things.  If you have any questions about why I did it that way, please post back and I'll try to help.  You can see that script in action on my server here:
http://www.laprbass.com/RAY_form_highlight_errors.php 

If you are new to PHP this book is an excellent learning resource.
http://www.sitepoint.com/books/phpmysql4/

As you get some more experience, this book will be a good addition to your library.
http://www.amazon.com/dp/0672328887

And going forward, if you use the code snippet feature to post your code here at EE, it will be easier for us to read and copy, and we will see line numbers which will make it easier for us to discuss specific parts of the code.

Best regards, ~Ray

Author

Commented:
Couldn't find the code snippet button anymore and now cannot find a way to search for a post by id. Guess I'm not too happy with the site's layout changes...

How do I search for a post by ID or can you otherwise provide an url?

Thanks.
Most Valuable Expert 2011
Top Expert 2016

Commented:
I use CTRL-F in my browser and look for the string that contains the ID number.  EE does not give us a way to have a link to a specific ID, in spite of thousands of requests for this tiny little convenience.  FWIW I am not really happy with the layout either.  It has made it harder for me to answer questions, so I do not answer as many as I could before the changes.  And I do not see much, if any, added value in the user experience.  Oh, well.

Author

Commented:
Well I bought the first of the two books you suggested. There I also find the following example on form evaluation:
<form action="welcome4.php" method="get">
<div><label for="firstname">First name:
<input type="text" name="firstname" id="firstname"/></label>
</div>
<div><label for="lastname">Last name:
<input type="text" name="lastname" id="lastname"/></label></div>
<div><input type="submit" value="GO"/></div>
</form>

Open in new window

also referring away from the form page itself for 'action'. Actually I see it that way in every beginners text I read. In your post ID 37851342 you wrote I should ask if I don't understand why you do it the way you do. Well I don't. Can you explain?
Most Valuable Expert 2011
Top Expert 2016

Commented:
Sure.  If you have the form and the action script in separate files, you have twice as many places to work when you need to make updates.  Technically there is nothing wrong with using separate scripts, but I find that using a single script keeps my work better organized.  It's just one of those things that grew into a useful habit for me.  Like using coding standards, it seems to be helpful.

Author

Commented:
In this page I first ask to select for a 'deelnemer' :

preselection
and then show the form, in table form, where the values have to be entered:

table form
Would you in your approach combine that in one code file as I did or create separate php-files, one per form?
Most Valuable Expert 2011
Top Expert 2016

Commented:
I would probably create one PHP/HTML file for each expected HTTP request.  In other words, the first script will select deelnemer and this selection will be passed to the second script.

Author

Commented:
Thanks again.

The book you recommended favors splitting html and php code into separate files: a php template containing the html (named e.g. form.html.php and put in a subdirectory named prognose e.g. in this case) code and a minimum of php on the one hand and a pure php script file on the other hand. You do not seem to be in favor of that approach (at least you don't bring it into practice in your code example).

Would you consider that approach  bad practice and if so why is your approach the better one?
Most Valuable Expert 2011
Top Expert 2016

Commented:
No, I do not consider it bad practice, however in my experience I have found it to be easier to keep my work organized with a single code file for both the action script and the HTML form.  Often I find myself writing a page that needs to query the data base, custom tailor the form for the client, present the form, and then process the submitted form.  At one time I thought it would be easier to separate these things into separate scripts, andI have done that in many web applications.  But over time I have come to find that more scripts means more work.  With everything in one script file, I rarely find myself having to open lots of windows to check variable names and things like that.

Author

Commented:
Well... I rewrote the new first script (the select deelnemer part) in what I think is the way you showed. Can you comment on that? Further recommendations / improvements?

What is a good way to take header, footer, navigation parts out of the code in this approach? Include a separate php file e.g. layout.inc.php containing the code like
<?php
$html_header = <<<HTMLHEADER
<html>
etc
HTMLHEADER;
$html_footer = <<<HTMLFOOTER
etc
</html>
HTMLFOOTER;
?>

Open in new window


Or without the opening en closing php tags there (as a pure text file), named layout.inc (without .php)?

And than echoing
echo $html_header.$html_page.$html_footer;

Open in new window

instead of only
echo $html_page;

Open in new window


<?php
session_start();
ini_set('display_errors', 'On');
error_reporting(E_ALL);
$menu_item_visibility = (isset($_POST)) ? 'visible' : 'hidden';

$deelnemer = (isset($_POST["deelnemer"])) ? addslashes($_POST["deelnemer"]) : NULL;

include("includes/verbinding.inc.php");

$sql = "SELECT deelnrId, voornaam, tv, achternaam, email FROM `deelnemer` ORDER BY achternaam";
$deelnemerkeuzelijst = mysql_query($sql);

$verbreken = mysql_close($verbinding);	
// deelnemerlijstje vullen voor dropdown veld
$select_lines = "";
while ($row = mysql_fetch_row($deelnemerkeuzelijst) ) {
	$select_lines .= "<option value=\"".$row[0]."\">".$row[1];
	$select_lines .= ($row[2]!="") ? " ".$row[2] : "";
	$select_lines .= " ".$row[3]."</option>\n";
}

$html_page = <<<HTMLPAGE
<?xml version=\"1.0\" encoding=\"ISO-8859-1\"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN" "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
	<meta http-equiv="Content-Type" content="text/html;charset=ISO-8859-1" />
	<title>Voetbaltoto 2010 - CCS</title>
	<link rel="stylesheet" href="opmaak.css" type="text/css"/>		
</head>
<body>
	<style type="text/css">
	.menu_item { visibility:$menu_item_visibility; }
	</style>

	<div class="paginakopbox">
		<div class="paginakopcenterbox">
			<img style="float: left;" src="images/school_logo.gif" alt="paginakop" />
				<p class="paginakoptekst">Voetbaltoto 2010</p>
		</div>
	</div>

	<div id="dummypaginacenterbox">
		
		<div id="navigatiekolom">
			<ol>
				<li><a href="index.php">Home</a></li>
				<li><a href="ideeenbus.php">Idee&euml;nbus</a></li>
				<li>Deelnemer</li>
				<ol style="list-style-type: none;"> 
					<li><a href="deelnemer_toevoegen.php">Toevoegen</a></li>
					<li><a href="deelnemer_wijzigen.php">Wijzigen</a></li>
					<li><a href="deelnemer_verwijderen.php">Verwijderen</a></li>
				</ol>	
				<li>Prognose</>
				<ol>
					<li><a href="prognose_wijzigen.php">Per stuk</a></li>
				</ol>
				<li><a href="wedstrijd.php">Wedstrijden</a></li>
				</li>
			</ol> 
		</div>
		
		<!-- breedte in afwijking van css -->
		<div id="paginainhoudbox" style="width: 745px"> 
			<h1>Prognose wijzigen</h1>
			<!-- invoerveldje laten zien voor selectie deelnemer -->
			<form style="width: 625px; " method="post" action="prognose.php">  
				<div style="width: 605px; padding-top: 15px;">
					<span style="float: left; width: 100px;">Deelnemer :</span>
					<select style="float: left; width: 200px;" name="deelnemer">
						{$select_lines}
					</select>
					<input style="margin-left: 15px;" type="submit" value="Selecteer" name="selectie" />
				</div>	
			</form>
		</div> 
	</div>
	 
	<div id="footer" class="footerbox"> 
		<div class="footercenterbox">
			<a href="index.php">Home</a>
			&nbsp;&nbsp;<a href="ideeenbus.php">Idee&euml;nbus</a>
			&nbsp;&nbsp;<a href="deelnemer_toevoegen.php">Dn toev</a>
			&nbsp;&nbsp;<a href="deelnemer_wijzigen.php">Dn wijz</a>
			&nbsp;&nbsp;<a href="deelnemer_verwijderen.php">Dn verw</a>
			&nbsp;&nbsp;<a href="prognose_wijzigen.php">Pr pstk</a>
			&nbsp;&nbsp;<a href="wedstrijd.php">Wedstrijden</a>
			<br />
			<p>
				<a href="http://validator.w3.org/check?uri=referer"><img
					src="http://www.w3.org/Icons/valid-xhtml11"
					alt="Valid XHTML 1.1" height="31" width="88" /></a>
			</p>
		</div>
	</div> 
</body>
</html>
HTMLPAGE;

echo $html_page;
?>

Open in new window

Most Valuable Expert 2011
Top Expert 2016

Commented:
Header, footer and navigation blocks are commonly separated into their own PHP files.  You want to avoid the use of the ?> tag unless it is absolutely necessary because of HTML or XML document information following it.  In other words, omit the close-PHP tag at the end of your scripts.  The reasons for this are complicated, but it should be one of your coding standards.

Have we answered the question about Warning: Cannot modify header information?

Author

Commented:
The issue is not solved yet but I think we're almost there...

Referring to your comment ID 37855528, here's the second script, rewritten according to your example code.

In your code the original form is not included, only the evaluation. Does that mean you advise to split the form and the evaluation of a form into separate files? Or how else would you advise to proceed from following code onward without using the solution as provided by the tutotial as quoted in post ID 37850628? (See specifically the else block from line 97-100.)

<?php
session_start();
ini_set('display_errors', 'On');
error_reporting(E_ALL);
$menu_item_visibility = (isset($_POST)) ? 'visible' : 'hidden';
if (!isset($_SESSION['deelnemer'])) { $_SESSION['deelnemer'] = $_POST["deelnemer"];	}
$deelnemer = $_SESSION['deelnemer'];

// fill field values from database
include_once "includes/page_layout.inc.php";

if (!isset($_SESSION['aPrognoses_old'])) { $_SESSION['aPrognoses_old'] = array(); } 
if (!isset($_SESSION['aPrognoses_new'])) { $_SESSION['aPrognoses_new'] = array(); } 
if (!isset($aPrognoses)) {
	include("includes/verbinding.inc.php");
	$sql = "SELECT scores.WedstrijdId, ScoreId, Dag, Datum, Tijd, Team1, Team2, IF(ISNULL(Prognose1),\"\",Prognose1) AS Prognose1, IF(ISNULL(Prognose2),\"\",Prognose2) AS Prognose2 
	FROM `scores` 
	LEFT OUTER JOIN `wedstrijd` 
	ON wedstrijd.WedstrijdId=scores.WedstrijdId 
	WHERE DeelnrId=".$deelnemer." 
	ORDER BY scores.WedstrijdId";
	$prognoses = mysql_query($sql);
	$verbreken = mysql_close($verbinding);	// Verbreken van de verbinding met de database
	$aPrognoses[] = array();
	while ($row = mysql_fetch_row($prognoses) ) {
		$aPrognoses[$row[1]]['wedstrijdId'] = $row[0];
		$aPrognoses[$row[1]]['dag'] = $row[2];
		$aPrognoses[$row[1]]['datum'] = $row[3];
		$aPrognoses[$row[1]]['tijd'] = $row[4];
		$aPrognoses[$row[1]]['team1'] = $row[5];
		$aPrognoses[$row[1]]['team2'] = $row[6];
		$aPrognoses[$row[1]]['prognose1'] = $row[7];
		$aPrognoses[$row[1]]['prognose2'] = $row[8];
		}
	}
// fetch old or posted values into arrays (sessionvariables)
foreach($aPrognoses as $sKey => $sValue) {
	$_SESSION['aPrognoses_old'][$sKey] = $sValue;
	}
if (!isset($_POST["save"])) { // aPrognoses_new initieren om later alleen de GEWIJZIGDE velden te hoeven bijwerken
	foreach($aPrognoses as $sKey => $sValue) {
		$_SESSION['aPrognoses_old'][$sKey] = $sValue;
		}
	} 
else { // bijwerken van de velden prognose1 en prognose2 in aPrognose_new
 	foreach($_POST['prognose1'] as $sKey => $sValue) {
 	 	$scorenr = $_POST['scoreId'][$sKey];
 	 	$options = array(
		    'options' => array(
		        'min_range' => 0,
		        'max_range' => 20
		    ),
		);
		$prog1 = filter_var($sValue, FILTER_VALIDATE_INT, $options);
		$prog2 = filter_var($_POST['prognose2'][$sKey], FILTER_VALIDATE_INT, $options);
		$_SESSION['aPrognoses_new'][$scorenr]['prognose1'] = $prog1;
		$_SESSION['aPrognoses_new'][$scorenr]['prognose2'] = $prog2;
		}
	}

// validate in case something was posted
// echo '<pre>$_POST: '.print_r($_POST).'</pre>';
$error_lines = "";
if (isset($_POST["save"])) {
    // Arrays declareren voor opslag van fouten en data
    $aErrors = array();
	
    // Alle formuliervelden doorlopen en array $aErrors vullen
    $i = 0;
    $j = 0;
 	$options = array(
	    'options' => array(
	        'min_range' => 0,
	        'max_range' => 20
	    ),
	);

	foreach($_POST['prognose1'] as $sProg1) {
		$sProg2 = $_POST['prognose2'][$i];
	 	if ((!filter_var($sProg1, FILTER_VALIDATE_INT, $options) and $sProg1!='0') or 
		    (!filter_var($sProg2, FILTER_VALIDATE_INT, $options) and $sProg2!='0')) {
			if (empty($aErrors)) {
				$aErrors[$j] = 'Je hebt de prognose van wedstrijd '.$_POST['wedstrijdId'][$i];	
				}
			else {
				$aErrors[$j] .= ', '.$_POST['wedstrijdId'][$i];
				}
			}
		$i++;
		}
	if (!empty($aErrors)) {
		$aErrors[$j] .= ' niet (correct) ingevuld';
        foreach($aErrors as $sError) {
         	$error_lines .= "<p style=\"color:red\">".$sError."</p>\n";
        	}
		} else {
		// TODO: 
		// - store aPrognoses_new values in the database
		// - send e-mail with a copy of the stored prognoses
		// die();
		}
	}

// fill table contents into variable
$table_lines = "";
$even = true;		
foreach($aPrognoses as $iScoreId => $aPrognose) {
 	if ($iScoreId > 0) {
		if (!$even) { $even=true; $table_lines .= "<tr class=\"alternate\" style=\"font-weight: normal;\">"; }
		else { $even=false; $table_lines .= "<tr style=\"font-weight: normal;\">"; }
		$table_lines .= "<td>&nbsp;&nbsp;".$aPrognose['dag']."</td><td>&nbsp;&nbsp;".$aPrognose['datum']."</td><td>&nbsp;&nbsp;".$aPrognose['team1']."</td><td>&nbsp;&nbsp;".$aPrognose['team2']."</td>";
		$table_lines .= "<td>&nbsp;&nbsp;<input type=\"text\" size=\"2\" name=\"prognose1[]\" value=\"".$aPrognose['prognose1']."\" /></td>";
		$table_lines .= "<td>-&nbsp;&nbsp;<input type=\"text\" size=\"2\" name=\"prognose2[]\" value=\"".$aPrognose['prognose2']."\" />";
		$table_lines .= "<input type=\"hidden\" id=\"scoreId\" name=\"scoreId[]\" value=\"".$iScoreId."\" />";
		$table_lines .= "<input type=\"hidden\" id=\"wedstrijdId\" name=\"wedstrijdId[]\" value=\"".$aPrognose['wedstrijdId']."\" /></td>";
		$table_lines .= "</tr>\n"; 
		}
	}
unset($iScoreId);

$html_page = <<<HTMLPAGE
			<h1>Prognose wijzigen</h1>
			<!-- invoerveldje laten zien voor selectie deelnemer -->
			
			<form style="width: 730px; " method="post" action="#">  
			<table width="725px" border="0" cellpadding="0" cellspacing="0" style="background: #ECF6FF;">
				<tr>
					<td colspan="2">&nbsp;&nbsp;Datum</td><td colspan="2">&nbsp;&nbsp;Wedstrijd</td><td colspan="2">&nbsp;&nbsp;Prognose</td>
				</tr>
				{$table_lines}
			</table>
			<br />
			<div style="text-align: center;">
				<input type="submit" value="Opslaan" name="save" />
			</div>
			{$error_lines}
			</form>
HTMLPAGE;

echo $html_header.$html_page.$html_footer;

Open in new window

Most Valuable Expert 2011
Top Expert 2016

Commented:
The issue is not solved yet but I think we're almost there...
You're still getting cannot modify headers?  What is the line number?

Author

Commented:
Now I'm done, finalized the script in one file and tested for the solution to be the solution to my problem (now having added header() calls) and it seems to work fine for me. I'll post further questions in a new thread / new threads.

Thanks a lot for all your help!

Do more with

Expert Office
Submit tech questions to Ask the Experts™ at any time to receive solutions, advice, and new ideas from leading industry professionals.

Start 7-Day Free Trial