ruud00000
asked on
headers already sent error (PHP)
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\voetbaltot o\prognose .php:41) in C:\xampp\htdocs\voetbaltot o\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
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\voetbaltot
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
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=#');
header('Refresh: 3; url=#');
ASKER
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_METHO D'] == '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">'.$sErro r.'</p>';
}
}
}
else
{
// Verwerk.php mag nog niet bezocht worden, terug naar het formulier
header('Location: formulier.php');
}
?>
<?php
include '../../inc/stats.php';
// Controle of een formulier gepost is
if($_SERVER['REQUEST_METHO
{
// 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'].'</
}
else
{
// Fouten opgetreden: weergeven en terug naar formulier
header('Refresh: 3; url=formulier.php');
foreach($aErrors as $sError)
{
echo '<p style="color:red">'.$sErro
}
}
}
else
{
// Verwerk.php mag nog niet bezocht worden, terug naar het formulier
header('Location: formulier.php');
}
?>
ASKER
I tried adding ob_start(); but that doesn't seem to make a difference. Where exactly should the line be put?
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?
ASKER CERTIFIED SOLUTION
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
To YoderCM's comment, here is an example of a common error...
<?php $x = 3; ?>
<?php session_start(); // THIS INSTRUCTION FAILS
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!
ASKER
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?
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?
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.
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();
Just move your session start FIRST:
<?php session_start();
$x = 3;
<?php session_start();
$x = 3;
ASKER
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.gi f" alt="paginakop" />
<p class="paginakoptekst">Voe tbaltoto 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">Toevo egen</a></ li>
<li><a href="deelnemer_wijzigen.p hp">Wijzig en</a></li >
<li><a href="deelnemer_verwijdere n.php">Ver wijderen</ a></li>
</ol>
<li>Prognose</>
<ol>
<li><a href="prognose_wijzigen.ph p">Per stuk</a></li>
</ol>
<li><a href="wedstrijd.php">Wedst rijden</a> </li>
<li><?php if (isset($_POST["submit"])) { ?> <a href="prognose_wijzigen.ph p">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["deelnem er"]);
include("includes/verbindi ng.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($deelnemer keuzelijst ) ) {
echo '<option value="'.$row['0'].'">'.$r ow['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["deelnem er"]);
include("includes/verbindi ng.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=scor es.Wedstri jdId
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]]['weds trijdId'] = $row[0];
$aPrognoses[$row[1]]['dag' ] = $row[2];
$aPrognoses[$row[1]]['datu m'] = $row[3];
$aPrognoses[$row[1]]['tijd '] = $row[4];
$aPrognoses[$row[1]]['team 1'] = $row[5];
$aPrognoses[$row[1]]['team 2'] = $row[6];
$aPrognoses[$row[1]]['prog nose1'] = $row[7];
$aPrognoses[$row[1]]['prog nose2'] = $row[8];
}
// voor debuggen:
/*
echo '<pre>a:'.gettype($aProgno ses).'</pr e>';
echo '<pre>0:'.print_r($aProgno ses).'</pr e>';
echo '<pre>1:'.print_r($aProgno ses[961]). '</pre>';
echo '<pre>1:'.print_r($aProgno ses[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"> Da tum</td><t d colspan="2"> We dstrijd</t d><td colspan="2"> Pr ognose</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> '.$aProgn ose['dag'] .'</td><td > &nb sp;'.$aPro gnose['dat um'].'</td ><td>  ; '.$ aPrognose[ 'team1'].' </td><td>& nbsp;  ;'.$aProgn ose['team2 '].'</td>' ;
echo '<td> <input type="text" size="2" name="prognose1[]" value="'.$aPrognose['progn ose1'].'" /></td>';
echo '<td>- <input type="text" size="2" name="prognose2[]" value="'.$aPrognose['progn ose2'].'" />';
echo '<input type="hidden" id="scoreId" name="scoreId[]" value="'.$iScoreId.'" />';
echo '<input type="hidden" id="wedstrijdId" name="wedstrijdId[]" value="'.$aPrognose['wedst rijdId'].' " /></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($_SESSIO N['aProgno ses']).'</ pre>';
// echo '<pre>10:'.gettype($aProgn ose).'</pr e>';
*/
// 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($aError s).'</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@schaersvoor de.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>Y ear</th>
</tr>
<tr>
<td>Joe</td><td>3rd</td><t d>August</ td><td>197 0</td>
</tr>
<tr>
<td>Sally</td><td>17th</td ><td>Augus t</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">'.$sErro r.'</p>';
}
}
} // einde isset post save
//}
// Verbinding met de database maken
// include("includes/verbindi ng.inc.php ");
?>
</div>
</div>
<div id="footer" class="footerbox">
<div class="footercenterbox">
<a href="index.php">Home</a>
<a href="ideeenbus.php">Idee& euml;nbus< /a>
<a href="deelnemer_toevoegen. php">Dn toev</a>
<a href="deelnemer_wijzigen.p hp">Dn wijz</a>
<a href="deelnemer_verwijdere n.php">Dn verw</a>
<a href="prognose_wijzigen.ph p">Pr pstk</a>
<a href="wedstrijd.php">Wedst rijden</a>
<?php if (isset($_POST["submit"])) { ?> <a href="prognose_wijzigen.ph p">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>
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
<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.gi
<p class="paginakoptekst">Voe
</div>
</div>
<div id="dummypaginacenterbox">
<div id="navigatiekolom">
<ol>
<li><a href="index.php">Home</a><
<li><a href="ideeenbus.php">Idee&
<li>Deelnemer</li>
<ol style="list-style-type: none;">
<li><a href="deelnemer_toevoegen.
<li><a href="deelnemer_wijzigen.p
<li><a href="deelnemer_verwijdere
</ol>
<li>Prognose</>
<ol>
<li><a href="prognose_wijzigen.ph
</ol>
<li><a href="wedstrijd.php">Wedst
<li><?php if (isset($_POST["submit"])) { ?> <a href="prognose_wijzigen.ph
</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["deelnem
include("includes/verbindi
$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'
// 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($deelnemer
echo '<option value="'.$row['0'].'">'.$r
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["deelnem
include("includes/verbindi
$sql = "SELECT scores.WedstrijdId, ScoreId, Dag, Datum, Tijd, Team1, Team2, IF(ISNULL(Prognose1),\"\",
FROM `scores`
LEFT OUTER JOIN `wedstrijd`
ON wedstrijd.WedstrijdId=scor
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).'<
//$aPrognoses[$row[1]] = array ();
$aPrognoses[$row[1]]['weds
$aPrognoses[$row[1]]['dag'
$aPrognoses[$row[1]]['datu
$aPrognoses[$row[1]]['tijd
$aPrognoses[$row[1]]['team
$aPrognoses[$row[1]]['team
$aPrognoses[$row[1]]['prog
$aPrognoses[$row[1]]['prog
}
// voor debuggen:
/*
echo '<pre>a:'.gettype($aProgno
echo '<pre>0:'.print_r($aProgno
echo '<pre>1:'.print_r($aProgno
echo '<pre>1:'.print_r($aProgno
*/
/* 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"> Da
</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> '.$aProgn
echo '<td> <input type="text" size="2" name="prognose1[]" value="'.$aPrognose['progn
echo '<td>- <input type="text" size="2" name="prognose2[]" value="'.$aPrognose['progn
echo '<input type="hidden" id="scoreId" name="scoreId[]" value="'.$iScoreId.'" />';
echo '<input type="hidden" id="wedstrijdId" name="wedstrijdId[]" value="'.$aPrognose['wedst
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['
echo '<pre>6:'.gettype($_POST['
echo '<pre>6:'.gettype($_POST['
echo '<pre>7:'.print_r($_POST['
echo '<pre>8:'.print_r($_POST['
echo '<pre>8:'.print_r($_POST['
echo '<pre>9:'.gettype($_SESSIO
// echo '<pre>10:'.gettype($aProgn
*/
// Arrays declareren voor opslag van fouten en data
$aErrors = array();
$aData = array();
// Alle formuliervelden doorlopen
$i = 0;
$j = 0;
foreach($_POST['prognose1'
// 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'][$
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($aError
// 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@schaersvoor
$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
</tr>
<tr>
<td>Joe</td><td>3rd</td><t
</tr>
<tr>
<td>Sally</td><td>17th</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">'.$sErro
}
}
} // einde isset post save
//}
// Verbinding met de database maken
// include("includes/verbindi
?>
</div>
</div>
<div id="footer" class="footerbox">
<div class="footercenterbox">
<a href="index.php">Home</a>
<a href="ideeenbus.php">Idee&
<a href="deelnemer_toevoegen.
<a href="deelnemer_wijzigen.p
<a href="deelnemer_verwijdere
<a href="prognose_wijzigen.ph
<a href="wedstrijd.php">Wedst
<?php if (isset($_POST["submit"])) { ?> <a href="prognose_wijzigen.ph
<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>
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">
<?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">
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>';
}
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/">';
HTH, ~Ray
ASKER
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.gi f" alt="paginakop" />
<p class="paginakoptekst">Voe tbaltoto 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">Toevo egen</a></ li>
<li><a href="deelnemer_wijzigen.p hp">Wijzig en</a></li >
<li><a href="deelnemer_verwijdere n.php">Ver wijderen</ a></li>
</ol>
<li>Prognose</>
<ol>
<li><a href="prognose_wijzigen.ph p">Per stuk</a></li>
</ol>
<li><a href="wedstrijd.php">Wedst rijden</a> </li>
<li>';
if (isset($_POST["submit"])) {
echo '<a href="prognose_wijzigen.ph p">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["deelnem er"]);
include("includes/verbindi ng.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($deelnemer keuzelijst ) ) {
echo '<option value="'.$row['0'].'">'.$r ow['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["deelnem er"]);
include("includes/verbindi ng.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=scor es.Wedstri jdId
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]]['weds trijdId'] = $row[0];
$aPrognoses[$row[1]]['dag' ] = $row[2];
$aPrognoses[$row[1]]['datu m'] = $row[3];
$aPrognoses[$row[1]]['tijd '] = $row[4];
$aPrognoses[$row[1]]['team 1'] = $row[5];
$aPrognoses[$row[1]]['team 2'] = $row[6];
$aPrognoses[$row[1]]['prog nose1'] = $row[7];
$aPrognoses[$row[1]]['prog nose2'] = $row[8];
}
// voor debuggen:
/*
echo '<pre>a:'.gettype($aProgno ses).'</pr e>';
echo '<pre>0:'.print_r($aProgno ses).'</pr e>';
echo '<pre>1:'.print_r($aProgno ses[961]). '</pre>';
echo '<pre>1:'.print_r($aProgno ses[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"> Da tum</td><t d colspan="2"> We dstrijd</t d><td colspan="2"> Pr ognose</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> '.$aProgn ose['dag'] .'</td><td > &nb sp;'.$aPro gnose['dat um'].'</td ><td>  ; '.$ aPrognose[ 'team1'].' </td><td>& nbsp;  ;'.$aProgn ose['team2 '].'</td>' ;
echo '<td> <input type="text" size="2" name="prognose1[]" value="'.$aPrognose['progn ose1'].'" /></td>';
echo '<td>- <input type="text" size="2" name="prognose2[]" value="'.$aPrognose['progn ose2'].'" />';
echo '<input type="hidden" id="scoreId" name="scoreId[]" value="'.$iScoreId.'" />';
echo '<input type="hidden" id="wedstrijdId" name="wedstrijdId[]" value="'.$aPrognose['wedst rijdId'].' " /></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($_SESSIO N['aProgno ses']).'</ pre>';
// echo '<pre>10:'.gettype($aProgn ose).'</pr e>';
*/
// 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($aError s).'</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@schaersvoor de.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>Y ear</th>
</tr>
<tr>
<td>Joe</td><td>3rd</td><t d>August</ td><td>197 0</td>
</tr>
<tr>
<td>Sally</td><td>17th</td ><td>Augus t</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">'.$sErro r.'</p>';
}
}
} // einde isset post save
//}
// Verbinding met de database maken
// include("includes/verbindi ng.inc.php ");
echo
'
</div>
</div>
<div id="footer" class="footerbox">
<div class="footercenterbox">
<a href="index.php">Home</a>
<a href="ideeenbus.php">Idee& euml;nbus< /a>
<a href="deelnemer_toevoegen. php">Dn toev</a>
<a href="deelnemer_wijzigen.p hp">Dn wijz</a>
<a href="deelnemer_verwijdere n.php">Dn verw</a>
<a href="prognose_wijzigen.ph p">Pr pstk</a>
<a href="wedstrijd.php">Wedst rijden</a>
<?php if (isset($_POST["submit"])) { ?> <a href="prognose_wijzigen.ph p">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>';
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\"?>\
<!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
<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.gi
<p class="paginakoptekst">Voe
</div>
</div>
<div id="dummypaginacenterbox">
<div id="navigatiekolom">
<ol>
<li><a href="index.php">Home</a><
<li><a href="ideeenbus.php">Idee&
<li>Deelnemer</li>
<ol style="list-style-type: none;">
<li><a href="deelnemer_toevoegen.
<li><a href="deelnemer_wijzigen.p
<li><a href="deelnemer_verwijdere
</ol>
<li>Prognose</>
<ol>
<li><a href="prognose_wijzigen.ph
</ol>
<li><a href="wedstrijd.php">Wedst
<li>';
if (isset($_POST["submit"])) {
echo '<a href="prognose_wijzigen.ph
}
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["deelnem
include("includes/verbindi
$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'
// 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($deelnemer
echo '<option value="'.$row['0'].'">'.$r
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["deelnem
include("includes/verbindi
$sql = "SELECT scores.WedstrijdId, ScoreId, Dag, Datum, Tijd, Team1, Team2, IF(ISNULL(Prognose1),\"\",
FROM `scores`
LEFT OUTER JOIN `wedstrijd`
ON wedstrijd.WedstrijdId=scor
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).'<
//$aPrognoses[$row[1]] = array ();
$aPrognoses[$row[1]]['weds
$aPrognoses[$row[1]]['dag'
$aPrognoses[$row[1]]['datu
$aPrognoses[$row[1]]['tijd
$aPrognoses[$row[1]]['team
$aPrognoses[$row[1]]['team
$aPrognoses[$row[1]]['prog
$aPrognoses[$row[1]]['prog
}
// voor debuggen:
/*
echo '<pre>a:'.gettype($aProgno
echo '<pre>0:'.print_r($aProgno
echo '<pre>1:'.print_r($aProgno
echo '<pre>1:'.print_r($aProgno
*/
/* 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"> Da
</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> '.$aProgn
echo '<td> <input type="text" size="2" name="prognose1[]" value="'.$aPrognose['progn
echo '<td>- <input type="text" size="2" name="prognose2[]" value="'.$aPrognose['progn
echo '<input type="hidden" id="scoreId" name="scoreId[]" value="'.$iScoreId.'" />';
echo '<input type="hidden" id="wedstrijdId" name="wedstrijdId[]" value="'.$aPrognose['wedst
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['
echo '<pre>6:'.gettype($_POST['
echo '<pre>6:'.gettype($_POST['
echo '<pre>7:'.print_r($_POST['
echo '<pre>8:'.print_r($_POST['
echo '<pre>8:'.print_r($_POST['
echo '<pre>9:'.gettype($_SESSIO
// echo '<pre>10:'.gettype($aProgn
*/
// Arrays declareren voor opslag van fouten en data
$aErrors = array();
$aData = array();
// Alle formuliervelden doorlopen
$i = 0;
$j = 0;
foreach($_POST['prognose1'
// 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'][$
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($aError
// 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@schaersvoor
$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
</tr>
<tr>
<td>Joe</td><td>3rd</td><t
</tr>
<tr>
<td>Sally</td><td>17th</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">'.$sErro
}
}
} // einde isset post save
//}
// Verbinding met de database maken
// include("includes/verbindi
echo
'
</div>
</div>
<div id="footer" class="footerbox">
<div class="footercenterbox">
<a href="index.php">Home</a>
<a href="ideeenbus.php">Idee&
<a href="deelnemer_toevoegen.
<a href="deelnemer_wijzigen.p
<a href="deelnemer_verwijdere
<a href="prognose_wijzigen.ph
<a href="wedstrijd.php">Wedst
<?php if (isset($_POST["submit"])) { ?> <a href="prognose_wijzigen.ph
<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>';
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
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
ASKER
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.
How do I search for a post by ID or can you otherwise provide an url?
Thanks.
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.
ASKER
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>
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?
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.
ASKER
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.
ASKER
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?
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?
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.
ASKER
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
Or without the opening en closing php tags there (as a pure text file), named layout.inc (without .php)?
And than echoing
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;
?>
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;
instead of only echo $html_page;
<?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ë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>
<a href="ideeenbus.php">Ideeënbus</a>
<a href="deelnemer_toevoegen.php">Dn toev</a>
<a href="deelnemer_wijzigen.php">Dn wijz</a>
<a href="deelnemer_verwijderen.php">Dn verw</a>
<a href="prognose_wijzigen.php">Pr pstk</a>
<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;
?>
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?
Have we answered the question about Warning: Cannot modify header information?
ASKER
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.)
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> ".$aPrognose['dag']."</td><td> ".$aPrognose['datum']."</td><td> ".$aPrognose['team1']."</td><td> ".$aPrognose['team2']."</td>";
$table_lines .= "<td> <input type=\"text\" size=\"2\" name=\"prognose1[]\" value=\"".$aPrognose['prognose1']."\" /></td>";
$table_lines .= "<td>- <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"> Datum</td><td colspan="2"> Wedstrijd</td><td colspan="2"> 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;
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?
ASKER
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!
Thanks a lot for all your help!
ob_start();
That will prevent the browser output until the script is finished.