not sure if I can example this right...
alright what I have here now runs the loop to check the student# and email I used an $error_check = 0 and $error_check ++ to consider if there's an error. If there is then an error will show and something will be printed into an error.log if not then something like the .txt file is good will print out and prints the contents
But I just realized the script will only run properly IF there's an error in the first row of my .txt file or else if there's an error to my second+ rows of contents in my .txt file then for the correct message will print out with the first row of content AND the error message will print out too.
But of course I want it the script to run that even if the first row of contents has no error and some other rows have error then only the error message will be printed.
I think it should be something about where I put the scripts in the loop but somehow I keep on reading my script and no idea what I should change....
else //else file exist then.......else #1
{
$fileContents = file("./courses/" . $_GET["filename"]); //calls out the file into $fileContents[] array....so $fileContents[0] is like the first row of the contents
$datePrinted = false; //setting a flag first so the date will be print only once when there's error..being used later in the foreach loop
$error_message = false; //setting a flag so error message only show once and being used later in the foreach loop
$well_formed = false; //another flag to stop the looping message saying the file is correctly formed
$table = false;
$error_check = 0;
sort($fileContents);
foreach($fileContents as $row) //the contents will be then seen as $row
{
$column = preg_split("/,/", $row); //splits the row by , and name each array as $column
$error_log = fopen("./courses/path/error.log","a+") or die ("File can not be opened"); //creates/open an error.log file
if(!(isEmailAddressWellFormed($column[3])) || !(isStudentNumberWellFormed($column[0]))) //two functions calls from page4.php using preg_match to check email and student# validation
//if one of them do not validate the following will start
{
$error_check++;
if(!$error_message) //if this is false then the error message+link will show
{
echo "Errors have been found in " . $_GET['filename'] . "<br/><a href='./courses/path/error.log'>Click here for the log</a>";
$error_message = true; //since this is in a loop but doesn't need to print it out so many times so changing the value here to true so when this loop runs again if(!error_message) will not run again
}
if(!$datePrinted) //works as how error_message works. the date only print once by here
{
fwrite($error_log, date("F t, Y (h:i:s a)") . PHP_EOL);
$datePrinted = true;
}
if(!(isEmailAddressWellFormed($column[3]))) //checks again if the email is not valid then print the follow to error.log
{
fwrite($error_log, "Improper email address from" . $_GET["filename"] . " :" . PHP_EOL);
fwrite($error_log, "$column[2] $column[1] $column[3]" . PHP_EOL);
}
if(!(isStudentNumberWellFormed($column[0]))) //checks again if the student # is not valid then print the follow to error.log
{
fwrite($error_log, "Improper student numbers from" . $_GET["filename"] . " :" . PHP_EOL);
fwrite($error_log, "$column[2] $column[1] $column[0]" . PHP_EOL . "\n");
}
}
elseif($error_check == 0)
{
if(!$well_formed)
{
echo "<h1 style='color: red'>" . $_GET["filename"] . " is well formed.</h1>";
echo "<table>";
$well_formed = true;
}
echo $column[0];
echo $column[1];
echo $column[2];
echo $column[3];
}
}//closing foreach
fwrite($error_log, str_repeat("-",80) . PHP_EOL); //puts a line to separate the next error but each time the page runs this line will print even if there's no error
fclose($error_log);
if(!$table)
{
echo "</table>";
$table = true;
}
}//closing else #1
thanks in advance for people helping...thanks....
I added
$row = $column[0] . $column[1] . $column[2] . $column[3];
at the beginning of the foreach after the preg_split then at the bottom I changed to...
elseif($error_check == 0)
{
$row.=$row;
}
}//closing foreach
fwrite($error_log, str_repeat("-",80) . PHP_EOL); //puts a line to separate the next error but each time the page runs this line will print even if there's no error
fclose($error_log);
if($error_check == 0)
{
echo "<h1 style='color: red'>" . $_GET["filename"] . " is well formed.</h1>";
echo "<table>";
echo $row;
echo "</table>";
}
}//closing else #1
?>
but now it only prints out the second row in the contents O.o only have three rows of contents at the moment for testing....am I missing something minor here?
Related
I am trying to get a PHP file to read a specific line from a text file and then use that line in a string comparison for an if statement.
The second line in the textfield will always have one of two different values. Either &activeGame=0 or &activeGame=1.
The textfile:
boardarray=["NV", "SB", "VB", "NV"]
&activeGame=1
&activePlayer=V
The PHP-file:
$theFile = "test.txt";
$line = file($theFile);
echo $line[1]; //This will output "&activeGame=1" without quotation marks
if ($line[1] == "&activeGame=1") {
echo "The game is active";
} else {
echo "The game is not active";
}
Since echo $line[1] outputs &activeGame=1 I know that the PHP script can read the data from the text file.
The problem is that the if function will echo "The game is not active" and I cant figure out why.
EDIT
SOLUTION:
$theFile = "test.txt";
$line = file($theFile);
echo $line[1]; //This will output "&activeGame=1" without quotation marks
if (trim($line[1]) == "&activeGame=1") {
echo "The game is active";
} else {
echo "The game is not active";
}
The trim function on row 5 is what was missing.
Your problem is that every line of file ends with \n.
You can see it if you var_dump($line[1]) instead of echo it.
So real value for &activeGame=1 is &activeGame=1\n.
That's definitely not equals &activeGame=1.
So, before comparing - use trim function:
$theFile = "test.txt";
$line = file($theFile);
echo $line[1]; //This will output "&activeGame=1" without quotation marks
$line_one = trim($line[1]);
if ($line_one == "&activeGame=1") {
echo "The game is active";
} else {
echo "The game is not active";
}
First Problem was if you echo $line[1] then its value is "&activeGame=1 " ( Notice the whitespace at end . and the optimal Solution Code that will give you desired output is as below
<?php
$theFile = "test.txt";
$line = file($theFile);
echo trim($line[1]); //This will output "&activeGame=1" without quotation marks
$a=trim($line[1]);
$truestr="&activeGame=1";
if ($a == $truestr) {
echo "The game is active";
} else {
echo "The game is not active";
}
?>
OUTPUT
'&activeGame=1'The game is active
I would use parse_str this way even if there are more variables on that line you can always get that value. http://php.net/manual/en/function.parse-str.php
$theFile = "test.txt";
$line = file($theFile);
parse_str($line[1],$output);
if ($output['activeGame'] == 1) {
echo "The game is active";
} else {
echo "The game is not active";
}
I have a question and answer forum. A user may browse responses to questions and promote them if they wish. The code below outputs the different users that have promoted a given question - the users are in the array '$promoters' that is returned from the line $promoters = Promotion::find_all_promotions_for_response($response->response_id); . The foreach loop then goes through each and outputs them, styles by the css class "promoter list". Problem is this.....if I have one promoter I just want their name outputed (no problem with this). But if I have many I want to put a comma between each name and then none after the last name in the foreach loop. Straightforward problem but I failed to achieve this....I tried to add a count($promoters) line in an elseif condition so that if the array $promoters has more than one value, then it outputs the users fullname and then a comma, but of course the last name also has a comma after it which is wrong. How do you indentify the last iteration in a foreach loop and ask it to do something different with this.....
Many thanks guys...
<?php
$promoters = Promotion::find_all_promotions_for_response($response->response_id);
if(!empty($promoters)){
echo "<span class=\"promoted_by\">Promoted by </span>";
foreach($promoters as $promoter){
echo "<span class=\"promoter_list\">" . User::full_name($promoter->user_id) . ", </span>";
}
} else {
echo "";
};
?>
<?php
$promoters = Promotion::find_all_promotions_for_response($response->response_id);
if(!empty($promoters)){
echo "<span class=\"promoted_by\">Promoted by </span>";
foreach($promoters as $idx=>$promoter){
echo "<span class=\"promoter_list\">" . User::full_name($promoter->user_id);
if($idx < count($promoters) - 1) {
echo ", ";
}
echo "</span>";
}
} else {
echo "";
}
?>
UPDATE:
This is another way to do it using implode as suggested by #deceze:
<?php
$promoters = Promotion::find_all_promotions_for_response($response->response_id);
if(!empty($promoters)){
echo "<span class=\"promoted_by\">Promoted by </span>";
$htmlParts = array();
foreach($promoters as $idx=>$promoter){
$htmlParts[] = "<span class=\"promoter_list\">" . User::full_name($promoter->user_id);
}
echo implode(', </span>', $htmlParts) . '</span>';
} else {
echo "";
}
?>
The last foreach loop doesn't seem to echo the list I want, it doesn't print anything. How can I fix this? I know it's getting quite complicated but any help would be appreciated.
$allTroopsList = array();
$allMissionsList = array();
while ($mytroops = $alltroops->fetch_assoc())
{
$allTroopsList []= $mytroops;
}
while ($mymissions = $allmissions->fetch_assoc())
{
$allMissionsList []= $mymissions;
}
while($userintroop = $allUsersintroops->fetch_assoc())
{
if($userintroop['userid'] == $_SESSION['userid'])
{
echo "<ul class='troop'>";
echo "<li>" . $userintroop['troopid']. " </li>";
foreach($allTroopsList as $mytroops)
{
if($userintroop['troopid'] == $mytroops['troopid'])
{
echo "<li> Troop description: " . $mytroops['description']. " </li>";
foreach($allMissionsList as $mymissions)
{
if($mytroops['missionid'] == $mymissions['missionid'])
{
echo "<li> Missionname: " . $mymissions['missionname']. " </li>";
echo "<br/>";
echo "</ul>";
}
}
}
}
}
}
foreach($allUsers as $myotherusers)
{
if($userintroop['userid'] == $myotherusers['userid'])
{
echo "<li> other users: " . $myotherusers['username']. " </li>";
echo "<br/>";
}
}
This line:
while($userintroop = $allUsersintroops->fetch_assoc())
is fetching results from a database, right? That'd mean at some point you run out of rows to fetch, and $userintroop will become a boolean FALSE.
Then later on you try to do
if($userintroop['userid'] == $myotherusers['userid'])
which is wrong on two levels - $userintroop will NOT be an array at this point, so it could never have a ['userid'] parameter. And since it's the result of a failed fetch operation, never could have any value OTHER than a FALSE.
So that last loop does execute, but will never produce anything since the conditions for producing output are literally impossible to meet.
We're trying to put a while inside a while loop.
The first while is run through and the results are displayed in a list (139, 140, 141).
The list for the second while only displays one value (1ste troop).
These are the results:
139
1ste troop
140
141
So it seems that the second while is only executed once.
What can I do to fix this?
echo "<ul>";
while($user = $allUsersintroops->fetch_assoc())
{
if($user['userid'] == $_SESSION['userid'])
{
echo "<li>" . $user['troopid']. " </li>";
while ($mytroops = $alltroops->fetch_assoc())
{
if($user['troopid'] == $mytroops['troopid'])
{
echo "<li>" . $mytroops['description']. " </li>";
}
}
}
}
echo "</ul>";
The inner loop stops once fetch_assoc returns false... but that indicates the end of all found results and it doesn't have any rows left for the next iteration.
You should collect all the rows from $alltroops into an array once, then iterate over that:
echo "<ul>";
$allTroopsList = array();
while ($mytroops = $alltroops->fetch_assoc()) {
$allTroopsList []= $mytroops;
}
while($user = $allUsersintroops->fetch_assoc()) {
if($user['userid'] == $_SESSION['userid']) {
echo "<li>" . $user['troopid']. " </li>";
foreach($allTroopsList as $mytroops) {
if($user['troopid'] == $mytroops['troopid']) {
echo "<li>" . $mytroops['description']. " </li>";
}
}
}
}
echo "</ul>";
Additionally, you should consider adding some filtering to your $allUsersintroops query, because you are only using a part of the the returned rows, which means the rest of the rows are sent from the DB to your code for no reason, wasting time and bandwidth.
I have the following code with the if...else statement within a while loop.
$colour = array("50305A", "E33600", "DBDD02", "73BE58");
$nextcolr = next($colour);
if ($nextcolr == FALSE)
{
reset($colour);
echo current($colour);
}
else
{
echo next($colour);
}
I can't work out why what ever is in the else statement isn't being executed, even if I switch the two statements and reverse the operator. Could anyone help me?
The entire while loop:
while($row = mysql_fetch_array($result))
{
echo "by <a href='/neuro/profile.php?userid=$row[MemberID]'>" . $row['FirstName'] . " " . $row['LastName'] . "</a> on " . $row['Timestamp'] . " | " . $row['NumberOfComments'] . " comments.";
echo "<div id='blog' style='background-color:#";
if ($nextcolr == FALSE)
{
reset($colour);
echo current($colour);
}
else
{
echo next($colour);
}
echo "'><a href='blog.php?threadid=" . $row['tID'] . "'>" . $row['Title'] . "</a></div>";
}
$colour = array("50305A", "E33600", "DBDD02", "73BE58");
while ... {
$nextcolr = next($colour);
if ($nextcolr === FALSE)
{
reset($colour);
}
echo current($colour);
}
is how your while loop should look like. If I am right, you are also defining $colour in the while loop, which might cause problems.
If all this is in the while loop, then you are re-declaring the array on each iteration, thus returning the array internal pointer to the beginning with each iteration.
If you want to iterate this array multiple times, you could do it this way:
$colour = array("50305A", "E33600", "DBDD02", "73BE58");
$i = 0;
while ... {
...
echo $colour[$i++ % count($colour)];
...
}
So you don't need this if-else block.
The problem with your original while loop is that you never change the value of $nextcolr.
Thus, it always remains FALSE and the else part never gets executed.