I am brand new to PHP and I am not sure if my technique is even good practice, but my code worked until I added the || (!is_numeric($variable)) portions of my if-statements.
I tested to code by inserting letters into the number fields but ensuring that the length of the string was correct. When I do, the code runs the else-statement and echos ".$jname."added.....etc"". The mysqli_query is commented out for testing. I have tried different versions with more or less parenthesis.
Why won't is_numeric() catch my letters? Am I allowed to do multiple ! arguments in an if-statement?
<?Php
header('Refresh: 3; url=../job_table.php');
require 'connect.php';
$jname = mysqli_real_escape_string($db,$_POST['field1']);
$jname_length = 25;
$jwo = mysqli_real_escape_string($db,$_POST['field2']);
$jwo_length = 7;
$jpo = mysqli_real_escape_string($db,$_POST['field3']);
$jpo_length = 4;
$add_job_query = "INSERT INTO jobs (name, wo_no, po_no) VALUES ('$jname','$jwo','$jpo')";
if(($jname || $jwo || $jpo ) == "") {
echo "<center><h1>Please fill all fields!</h1></center>";
} elseif(!(strlen($jname) <= $jname_length)) {
echo "<center><h1>Name must be less than or equal to ".$jname_length." characters!</h1></center>";
} elseif((strlen($jwo) != $jwo_length) || (!is_numeric($jwo))) {
echo "<center><h1>WO number must be a ".$jwo_length." digit number!</h1></center>";
} elseif((strlen($jpo) != $jpo_length) || (!is_numeric($jwo))) {
echo "<center><h1>PO number must be a ".$jpo_length." digit number!</h1></center>";
} else {
//echo mysqli_query($db,$add_job_query);
echo "<center><h1>".$jname." added!</h1><h1>WO number:".$jwo."</h1><h1>PO number:".$jpo."</h1></center>";
}
echo "<center><h1>Please wait.</h1></center>";
?>
Seems to me that you need something like this instead.
if(empty($jname) || empty($jwo) || empty($jpo)){
echo "<center><h1>Please fill all fields!</h1></center>";
}elseif($jname <= $jname_length){
echo "<center><h1>Name must be less than or equal to ".$jname_length." characters!</h1></center>";
}elseif(($jwo != $jwo_length) || (!is_numeric($jwo))){
echo "<center><h1>WO number must be a ".$jwo_length." digit number!</h1></center>";
}elseif(($jpo != $jpo_length) || (!is_numeric($jwo))){
echo "<center><h1>PO number must be a ".$jpo_length." digit number!</h1></center>";
}else{
//echo mysqli_query($db,$add_job_query);
echo "<center><h1>".$jname." added!</h1><h1>WO number:".$jwo."</h1><h1>PO number:".$jpo."</h1></center>";
}
I am sorry to ask such a question but am bit confused about this.
I am having simple variables defined.
$a =1;
$b=2;
$c=3;
$d="";
for($i=0;$i<10;$i++)
{
$testa = 1;
$testb = 4;
$testc = 3;
$testd = 7;
if($a!="" || $b!="" || $c!="" || $d!="") {
if($a==$testa && $b==$testb && $c==$testc && $d==$testd) {
echo $testa;
echo $testb;
echo $testc;
echo $testd;
}
}
}
This is sample php code.
what I need is that I have variables defined at top. SO in my loop i want to display result if user has any 1 variable but in below loop display result based on "and" parameter.
I actually want to skip the empty variable. SO in this case, I want as $d is empty, so it should be prevented somehow from if($a==$testa && $b==$testb && $c==$testc && $d==$testd) from here.
Any help is really appreciated.
To skip the empty values from the check, use ||
if ( ... && (empty($d) || $d == $testd)) {
Then if you also want to skip it in your echos :
echo !empty($d) ? $testd : '';
I have string $a,$b,$c
I know if all of them not null express in this way:
if($a!="" && $b!="" && $c!="")
But if either 2 of them not null then go into the true caluse
if($a!="" && $b!="" && $c!=""){
** do the things here **
}else if(either 2 are not null){
**do another things here**
}
How to express it?
I would write a simple function like this to check:
function checkInput($var)
{
$nulls=0;
foreach($var as $val)
{
if(empty($val))
{
$nulls++;
}
}
return $nulls;
}
Then access it like this:
$inputs=array($a, $b, $c.... $z);
$nullCount=checkInput($inputs);
if($nullCount==0)
{
// All nulls
}
if($nullCount>2)
{
// More than 2 nulls
}
or for an one-off test, just pop the function into the actual if statement like this:
if(checkInput($inputs)>2)
{
// More than 2 nulls...
}
etc etc. You can then use the one function to check for any number of nulls in any number of variables without doing much work - not to mention change it without having to rewrite a long if statement if you want to modify it.
Other answers are good, but you can expand this to easily handle more variables:
$variables = array($a, $b, $c, $d, ....);
$howManyNulls = 0;
foreach($variables as $v){
if($v == ''){
$howManyNulls++;
}
}
if($howManyNulls == count($variables) - 2){
// do stuff
}
you can try this
if($a!="" && $b!="" && $c!="")
{
** do the things here **
}
else if(($a!="" && $b!="") || ($b!="" && $c!="") || ($a!="" && $c!=""))
{
**do another things here**
}
Try:
if($a!="" && $b!="" && $c!=""){
** do the things here **
}else if(($a!="" && $b!="") || ($a!="" && $c!="") || ($b!="" && $c!="")){
**do another things here**
}
$var[] = empty($a) ? 0:$a;
$var[] = empty($b) ? 0:$b;
$var[] = empty($c) ? 0:$c;
$varm = array_count_values($var);
if ($varm[0] === 0) {
//Code for when all aren't empty!
} elseif ($varm[0] === 1) {
//Code for when two aren't empty!
}
N.B; You may need to replace the 0 for a string/integer that will never crop up, if your variables are always strings or empty then 0 will do for this. The method for using bools within this would require more code.
$nullCount = 0
if($a!=""){ ++$nullCount; }
if($b!=""){ ++$nullCount; }
if($c!=""){ ++$nullCount; }
if($nullCount == 3){ // all are null
// do smth
}else if($nullCount == 2){ // only two are null
// do other
}
Just for fun, here's something potentially maintainable, should the list of arguments increase:
function countGoodValues(...$values) {
$count = 0;
foreach($values as $value) {
if($value != "") {
++$count;
}
}
return $count;
}
$goodValues = countGoodValues($a, $b, $c); // Or more... or less
if($goodValues == 3) {
// Do something here
}
else if($goodValues == 2) {
// And something else
}
Reference for the ... construct (examples #7 and #8 in particular) are available on php.net.
You can use double typecasting (to boolean, then to number) in conjunction with summing:
$count = (bool)$a + (bool)$b + (bool)$c;
if ($count == 3)
// ** do the things here **
else if ($count == 2)
//**do another things here**
There is also possible such solution:
<?php
$a= 'd';
$b = 'a';
$c = '';
$arr = array( (int) ($a!=""), (int) ($b!=""), (int) ($c!=""));
$occ = array_count_values($arr);
if ($occ[1] == 3) {
echo "first";
}
else if($occ[1] == 2) {
echo "second";
}
If you have 3 variables as in your example you can probably use simple comparisons, but if you have 4 or more variables you would get too big condition that couldn't be read.
if (($a!="") + ($b!="") + ($c!="") == 2) {
// two of the variables are not empty
}
The expression a!="" should return true (which is 1 as an integer) when the string is not empty. When you sum whether each of the strings meets this condition, you get the number of non-empty strings.
if (count(array_filter([$a, $b, $c])) >= 2) ...
This is true if at least two of the variables are truthy. That means $var == true is true, which may be slightly different than $var != "". If you require != "", write it as test:
if (count(array_filter([$a, $b, $c], function ($var) { return $var != ""; })) >= 2) ...
if($a!="" && $b!="" && $c!="") {
echo "All notnull";
} elseif(($a!="" && $b!="") || ($b!="" && $c!="") || ($a!="" && $c!="")) {
echo "Either 2 notnull";
}
I am having trouble with some if statements. To cut a long story short, when a certain statement is true, the code stops and doesn't move on to the next loop/series of if statements.
Here is the first statement that once reached, doesn't move on.
else if ((($pteam_score[$i] == $popposition_score[$i]) && ($pteam_score[$i] != 0) && ($popposition_score[$i] != 0))) {
$team_points[$i]-=2;
$opposition_points[$i]-=2;
$team_win[$i]-=0;
$team_draw[$i]-=1;
$team_loss[$i]-=0;
$team_extra[$i]-=0;
$opp_win[$i]-=0;
$opp_draw[$i]-=1;
$opp_loss[$i]-=0;
$opp_extra[$i]-=0;
$played[$i]-=1;
echo "hey";
$query9=$database->query("UPDATE results_a SET team_name='$team[$i]', team_score='$pteam_score[$i]',
opposition_score='$popposition_score[$i]', opposition_name='$opposition[$i]' where fixture_id='$fixture_id'");
}
And here is the second. Bare in mind there are about 20 of these ifs/else ifs/ and when any of the others are hit, the points are decucted (as they are with the two bad loops also) butit seems it doesn't then move on to a separate section of the code. Perhaps coincidentally, both bad loops involve a draw result!
else if ((($pteam_score[$i] == $popposition_score[$i]) && ($pteam_score[$i] != 0) && ($popposition_score[$i] != 0))) {
$team_points[$i]-=2;
$opposition_points[$i]-=2;
$team_win[$i]-=0;
$team_draw[$i]-=1;
$team_loss[$i]-=0;
$team_extra[$i]-=0;
$opp_win[$i]-=0;
$opp_draw[$i]-=1;
$opp_loss[$i]-=0;
$opp_extra[$i]-=0;
$played[$i]-=1;
echo "what?";
$query9=$database->query("UPDATE results_a SET team_name='$team[$i]', team_score='$pteam_score[$i]',
opposition_score='$popposition_score[$i]', opposition_name='$opposition[$i]' where fixture_id='$fixture_id'");
}
Can anybody see any reason the code would stop dead with the above two statements? The echo stuff is just to see which option is hit. As I said, these two loops are hit at the correct times, but they are the only two that seem to stop the process.
EDIT - A SECTION THAT WORKS FINE
if (($team_score[$i] == $pteam_score[$i]) && ($opposition_score[$i] == $popposition_score[$i])) {
$team_points[$i]+=0;
$opposition_points[$i]+=0;
$team_win[$i]+=0;
$team_draw[$i]+=0;
$team_loss[$i]+=0;
$team_extra[$i]+=0;
$opp_win[$i]+=0;
$opp_draw[$i]+=0;
$opp_loss[$i]+=0;
$opp_extra[$i]+=0;
$played[$i]+=0;
echo "0";
$query11=$database->query("UPDATE results_a SET team_name='$team[$i]', team_score='$pteam_score[$i]',
opposition_score='$popposition_score[$i]', opposition_name='$opposition[$i]' where fixture_id='$fixture_id'");
}
else if (($pteam_score[$i] == 0) && ($popposition_score[$i] == 0)) {
$team_points[$i]+=0;
$opposition_points[$i]+=0;
$team_win[$i]+=0;
$team_draw[$i]+=0;
$team_loss[$i]+=0;
$team_extra[$i]+=0;
$opp_win[$i]+=0;
$opp_draw[$i]+=0;
$opp_loss[$i]+=0;
$opp_extra[$i]+=0;
$played[$i]+=0;
echo "bla";
}
if (($pteam_score[$i] != $team_score[$i]) && ($popposition_score[$i] == $opposition_score[$i])) {
if (($pteam_score[$i] > $popposition_score[$i]) && ($pteam_bonus[$i] > $popposition_score[$i])) {
$team_points[$i]-=3;
$opposition_points[$i]-=0;
$team_win[$i]-=1;
$team_draw[$i]-=0;
$team_loss[$i]-=0;
$team_extra[$i]-=0;
$opp_win[$i]-=0;
$opp_draw[$i]-=0;
$opp_loss[$i]-=1;
$opp_extra[$i]-=0;
$played[$i]-=1;
echo "6";
$query5=$database->query("UPDATE results_a SET team_name='$team[$i]', team_score='$pteam_score[$i]',
opposition_score='$popposition_score[$i]', opposition_name='$opposition[$i]' where fixture_id='$fixture_id'");
}
Thanks in advance
I have a function that will take an id and with that find out other information in the database relating to it spread among 3 tables. It then compares this to a csv file which at most times is cpu intensive. Running this once with one id takes approx 8 to 10 sec at most but I have been asked to have it run automatically across a varing number of ids in the database. To do this I created an array of the ids that match the criteria in the database at any point and then run a 'while' statement to repeat the function for each element in the array but it gets as far as maybe 4 of them and I get the following error:
Server error!
The server encountered an internal error and was unable to complete
your request. Either the server is overloaded or there was an error in
a CGI script.
If you think this is a server error, please contact the webmaster.
Error 500
I'll admit that my code could be much much cleaner as I'm still learning as I go but the real bottle neck appears to be reading the csv which is a report which size changes each day. I have tried different combinations and the best result is (please don't chastise me for this as I know it is stupid but the other ways haven't works as of yet) to run the code as follows:
$eventArray = eventArray($venueId);
$totalEvents = count($eventArray);
for($i=0; $i<$totalEvents; $i++)
{
$eventId = $eventArray[$i];
echo $eventId;
echo $datename = getEventDetails($eventId, $zone);
// date of event
echo $eventDate = $datename['eventDate'];
// vs team
echo $eventName = $datename['eventName'];
$file_handle = fopen("data/rohm/sales/today.csv", "r");
while (!feof($file_handle) )
{
$line_of_text = fgetcsv($file_handle, 200);
include('finance_logic.php');
}
fclose($file_handle);
}
Yes, it is repeating the reading of the csv every time but I couldn't get it to function at all any other way so if this is the issue I would really appreciate some guidence on dealing with the csv better. Incase it is relevent the code it 'finance_logic.php' is listed below:
if($line_of_text[0] == "Event: $eventName ")
{
$f = 1;
$ticketTotalSet = "no";
$killSet = 'no';
// default totals zero
$totalHolds = 0;
$totalKills = 0;
$ticketSold = 0;
$ticketPrice = 0;
$totalCap = 0;
}
if($f == 1 && $line_of_text[0] == "$eventDate")
{
$f = 2;
}
if($f == 2 && $line_of_text[0] == "Holds")
{
$f = 3;
while($line_of_text[$col] !== "Face Value Amt")
{
$col++;
}
}
if($f == 3 && $line_of_text[0] !== "Face Value Amt")
{
if($f == 3 && $line_of_text[0] == "*: Kill")
{
$totalKills = $line_of_text[$col];
}
$holdsArray[] = $line_of_text[$col];
}
if($f == 3 && $line_of_text[0] == "--")
{
$f = 4;
}
if($f == 4 && $line_of_text[0] == "Capacity")
{
$totalCap = $line_of_text[$col];
$f = 5;
}
if($f == 5 && $line_of_text[0] == "Abbreviated Performance Totals")
{
$f = 6;
}
if($f == 6 && $line_of_text[0] == "$eventName")
{
// change when 1 ticket exists
$ticketTotalSet = "yes";
// set season tickets
include("financial/seasontickets/$orgShortName.php");
// all non season are single tickets
if(!isset($category))
{
$category = 'single';
}
$ticketName = $line_of_text[2];
$ticketSold = $line_of_text[3];
$ticketPrice = $line_of_text[4];
addTicketType($eventId, $ticketName, $category, $ticketSold, $ticketPrice);
unset($category);
}
if($f == 6 && $ticketTotalSet == "yes" && $line_of_text[0] !== "$eventName")
{
$totalHolds = (array_sum($holdsArray) - $totalKills);
// add cap, holds and kills
addKillsHoldsCap($eventId, $totalCap, $eventId, $totalHolds, $totalKills);
// reset everything
$f = 0;
$ticketTotalSet = "no";
echo "$eventName updated!";
}
Thanks in advance!
p.s. The reason the report is called each time is so that the 'eventName' and 'eventDate' are searched for with the 'finance_logic.php'. Obviously if this was set with all event names and dates already it would take one search of the report to find them all but I'm not sure how I could do this dynamically. Any suggestions would be welcome as I'm sure there is something out there that I just haven't learnt yet.
I have some heavy script i use with localhost sometimes and if i don't add anything they will just time out.
A simple solution is to limit the number of execution of your function, then reload the page, then restart where you stopped.