Is there something in php that can halt or let the script proceed if things are ok?
In my current scripts I do like this (for this example):
$fetch = false;
if($i == 10){
echo 'I is clear'
$fetch = true;
}
if($fetch){
//Do database work here
}
echo 'This should be seen no matter what the above';
Instead of the $fetch in there, can I do something else? I don't want to stop the entire script after that like what die() or exit does.
Here's an example that should help you:
<?php
function doLoop() {
for($i=0;$i<100;$i++) {
if($i != 50) {
continue; //It's not 50, skip it
}
//Otherwise
printf("Loop: $i");
}
}
function doBreak() {
for($i=0;$i<100;$i++) {
if($i != 49) {
continue; //It's not 49 yet, continue
} //Otherwise, break
printf("Loop: $i");
break;
}
}
doLoop();
doBreak();
?>
break; can be used to end a loop when a condition is met, while continue; can also be used to skip a certain value if a condition is not met. Using die(); would stop your whole script from executing, preventing it to call anything that comes after the die(); statement because that's how the execution of the scripts pretty much go, from the top to the end.
Related
I am trying to make a registration system with text files and I need help with using an else statement after the loop that checks if the username is taken.
I am generally just trying to find out how to have an else statement after a loop with an if statement, if I find out that out my problem is basically solved. Here is the code:
while($i < count($logindata)-1) {
if ($_POST['username'] == $user[$i]['username']) {
set_message(" That username is taken", "danger");
}
$i++;
}
else {
if (!empty($_POST['username']) && !empty($_POST['password'])) {
file_put_contents('logininformation.txt', $_POST['username'] . "?=%&$##[}[}+-789409289746829" . $_POST['password'] . "\n", FILE_APPEND);
set_message("Account created!", "success");
} else {
set_message(" You have not put in a username and/or password","danger");
}
}
I expect to be able to have an else statement after the loop and it working.
A loop is not a condition, therefore it does not have an else part either. It is correct that the loop runs while the condition evaluates to true, but as soon as the condition does not evaluate to true, the loop is ended.
Therefore, to check whether the loop was not triggered at all, you have to find a different way, e.g. write a condition on its own.
For the sake of argument, you COULD save a flag and evaluate that afterwards, but in most cases I would not recommend that:
$i = 0;
$loopDidRun = false;
while ($i < 10) {
$i++;
$loopDidRun = true;
}
if (!$loopDidRun) {
echo "loop did not run, therefore the 'else case', but not really";
}
Your logic is severely flawed.
$failed=false;
if(empty($_POST['username']) || empty($_POST['password'])){
$failed=true,
set_message(" You have not put in a username and/or password","danger");
}else{
while($i<count($logindata)-1){
if($_POST['username']==$user[$i]['username']){
$failed=true;
set_message("That username is taken","danger");
break;
}
$i++;
}
}
if(!$failed){
file_put_contents('logininformation.txt',$_POST['username']."?=%&$##[[}+-789409289746829".$_POST['password']."\n",FILE_APPEND);
set_message("Account created!","success");
}
However all I am doing here is fixing bad code. Before anything you need to filter the $POST input given to disallow just any input, passwords etc. should not be stored in plain text, and this is not the proper way of creating a factory for this. You should find better, and secure, examples online and work from them.
I've got the following code:
$counter = 0;
while($currentPage <= $pages) {
sleep(0.1);
flush();
$browseNodeLookup->setPage($currentPage);
try {
$xml = $apaiIO->runOperation($browseNodeLookup);
} catch(Exception $e1) {
if($counter == 20) {
break;
}
}
if($xml) {
$all_elements = iq_parse_data($xml, $itemcount, $all_elements);
$currentPage++;
} else {
if($counter == 20) {
break;
}
}
$counter++;
}
By now it looks a little bit weird already, because I just can't get that while loop to break. The problem is, my website suddenly(without any change by myself) crashed. What I did was to just remove the while loop and the website worked again. Now the problem is, sometimes the page loads, and sometimes it doesn't.
When it doesn't the script continues for so long, that with multiple clients, the server crashes and I have to manually restart apache.
Is there anything wrong with this while loop? Did I miss something?
EDIT:
I found out the mistake, it wasn't even about my while loop(allthough the fix with counter <= 20 is also true). It was about guzzle, which makes the request behind "runOperation". I had to define a timeout, because I don't know why, but it seems that something with Amazon Product API changed, so that there could be an infinite loop in guzzle.
The fix was this:
$client = new \GuzzleHttp\Client(['timeout' => 2.0]);
I should provide the whole code next time, maybe someone would have spotted this. Thank you guys.
The most likely explanation is that your code is not actually hitting your break, because the counter gets incremented every iteration, but you are only checking for exactly 20 when it's not an actual page
The following code should be changed to change this issue:
if($counter >= 20) {
break;
}
Currently your code looks a little complicated. You can simplify it in this way:
while($currentPage <= $pages) {
sleep(0.1);
flush();
$browseNodeLookup->setPage($currentPage);
try {
$xml = $apaiIO->runOperation($browseNodeLookup);
$all_elements = iq_parse_data($xml, $itemcount, $all_elements);
} finally {
$currentPage++;
}
}
From the looks of it, you're only breaking when ($counter == 20 && !$xml). You're never advancing $currentPage if that condition isn't true, so the loop will be stuck forever.
Edit for clarity:
It's likely that $counter has passed 20 by the time that $xml is falsy, which means $currentPage isn't advancing (so your while condition is still true) but because $counter is greater than 20, your break does not get hit. Change $counter == 20 to $counter >= 20.
Also if you're trying to just advance until you either hit 20 or $totalPages, whichever is lower, your code could be simplified to something like
$pages = min(20, $pages);
while ($currentPage <= $pages) {
sleep(0.1);
flush();
$browseNodeLookup->setPage($currentPage);
try {
$xml = $apaiIO->runOperation($browseNodeLookup);
$all_elements = iq_parse_data($xml, $itemcount, $all_elements);
} catch (Exception $e1) {
// Any error handling you want to do
}
$currentPage++;
}
I just started learning php and I have to do something like this which I got it working but I just have a few questions I want to ask for alternate way of doing but eh first of all the br/ is suppose to be with <> but somehow if i do that the coding at the bottom will see it as a line break.
Anyways if questions are...
With the coding below the outcome will be 0-9 (without 5) but I have to set $zero=-1 if I put $zero=0 then the outcome would be 1-9 (without 5) is there a way I don't have to make $zero=-1 and still have the outcome of 0-9 (without 5)?
I realized I have to put $zero++ before the if and continue statement if I put it at the end of the script after echo "$zero" . "br/"; the script won't run as wanted. Is this how it is suppose to be or I just don't know the other way of doing it.
Thanks in advance for people replying ^_^
$squared = pow(3,2);
echo "\"3 squared is $squared:";
echo "br/";
$zero = -1;
while ($squared > $zero)
{
$zero++;
if ($zero == 5)
{
continue;
}
else if ($squared == $zero)
{
echo "$squared\"";
}
else
{
echo "$zero" . "br/";
}
}
Here it is (you were almost there :P )
$nr = 0;
while ($squared > $nr) {
if (5 == $nr) {
$nr++; // add this
continue;
} else if ($squared == $nr) {
echo "$squared\"";
} else {
echo "$nr" . "<br/>";
}
$nr++; // move to the bottom
}
PS: You're welcome #clement
Change your while loop to while ($squared >= $zero) and then set $zero = 0;
Should work!
I know there must be a nicer way to do this, but whenever I search "&&" i don't get good enough results...
<?php
if (empty($row[ContactName]) && empty($row[ContactEmail]) && empty($row[ContactPhone]) && empty($row[Website])){
echo "Not Provided";
}
else{
...do stuff...
}
?>
Thanks!
What is wrong with the original code?
<?php
if (empty($row[ContactName])
&& empty($row[ContactEmail])
&& empty($row[ContactPhone])
&& empty($row[Website]))
{
echo "Not Provided";
}
else{
...do stuff...
}
?>
Looks like fine code to me...
<?php
$i=1;
$ar=array('ContactName','ContactEmail','ContactPhone','Website')
foreach($ar as $a)
if (empty($row[$a]))
{
$i=0;
break; //to make code fast
}
if($i) //do stuff
else echo 'not provided';
?>
or if you really want to make your code extra small then change your column name in database
From To
ContactName Col1
ContactEmail Col2
ContactPhone Col3
Website Col4
and then do
<?php
$i=1;
for($a=1;$a<5;$a++)
if (empty($row['Col'.$a]))
{
$i=0;
break;
}
if($i)//do stuff
else echo 'Not Provided';
?>
However it is not good to rename column as it will make your db somewhat less understandable.
As php functions have a lot of inconsistency, It's always a good idea using a library to make it more consistent.
put this function in that library:
function empty()
{
foreach(func_get_args() as $arg) if (empty($arg)) return false;
return true;
}
usage:
if (empty($row[ContactName], $row[ContactEmail], $row[ContactPhone], $row[Website])) {
echo "Not Provided";
}
you could make it as short as this if compactness was more important than readability :)
$required = array('ContactName', 'ContactEmail', 'ContactPhone', 'Website');
$ra = array_filter(array_intersect_key($row,array_flip($required)));
if(empty($ra)){
echo "Not Provided";
}
else{
//....
}
you can't put array_filter inside empty() or you get "Fatal error: Can't use function return value in write context"
1) array flip is turning your $required values into keys
2) array_intersect_key throws away any $row keys not found in $required
3) array_filter throws away any empty values
leaving you with a zero length array, which is empty. No need to worry about array lengths or loops
<?php
$flag = 1;
if (empty($row[ContactName])){
$flag = 0;
}
if (empty($row[ContactEmail])){
$flag = 0;
}
if (empty($row[ContactPhone])){
$flag = 0;
}
if (empty($row[Website])){
$flag = 0;
}
if($flag == 0){
echo "Not Provided";
}else{
//do stuff
}
?>
OR
$flag = 1;
$i=0;
$mustarray = array('ContactName','ContactName','ContactName','ContactName'); //or any number of fields that you want as mandatory
foreach($yourresult as $row){
if(empty($row[$mustarray [$i]])){
$flag = 0;
}
$i++;
}
if($flag == 0){
echo "Not Provided";
}else{
//do stuff
}
Do not play with making arrays and stuff just to make code look nicer.
As Tommy pointed
<?php
if (empty($row[ContactName])
&& empty($row[ContactEmail])
&& empty($row[ContactPhone])
&& empty($row[Website]))
{
echo "Not Provided";
}
else{
...do stuff...
}
?>
this code is nice, just need proper formatting like he pointed.
Making arrays and then launching loop will decrease performance
<?php
$i=1;
for($a=1;$a<5;$a++)
if (empty($row['Col'.$a]))
{
$i=0;
break;
}
if($i)//do stuff
?>
this might look small, nice and "pro", but has more operations to give same results as a simple if instruction.
Not saying that it cant be done faster, i don't know php well, just remember about code executing speed.
no idea how to ask this question... the problem is that I need to stop the loop from runing if if ($current[$id][$i]['item'] == '') is true, so whatever the script needs to do or in this case echo, don't get repeated 15 times.
If using exit; the whole page will stop to render, so, any ideas ?
Thanks in advance.
If the question is not clear enough don't hesitate to ask using the comments, I will more than happy to clarify any doubts.
$i=1;
while($i<=15) {
if ($current[$id][$i]['item'] == '') {
echo 'Done!.';
//do something
}
$a++;
}
use break
$i=1;
while($i<=15) {
if ($current[$id][$i]['item'] == '') {
echo 'Done!.';
break;
}
$i++; //<- that should probably be $i instead of $a?
}
How about using the break control structure?
You need to break. Also, your current loop is endless and will therefore time-out. Presumably you meant to increment $i, not $a.
$i=1;
while($i<=15) {
if ($current[$id][$i]['item'] == '') {
echo 'Done!.';
break; //<-- terminate loop
}
$a++; //<-- shouldn't this be $i++?
}
There is only 2 ways to break a loop... using exit; and break;....
break; is what you want it will exit the loop and continue execution, exit will end the script.
$i=1;
while($i<=15) {
if ($current[$id][$i]['item'] == '') {
echo 'Done!.';
break; // or you can make value of $i = 20;
}
$a++;
}