php. if conditions - php

This seems simple but I don't know why it doe snot work.
I need to write an if statement that
first, checks if it is numeric
second, if it is not between 1 and 10, issue errorA
third, if it is not between 20 and 30, issue errorB
fourth, it is not a number, issue errorC
If is not numeric and satisfies all the ranges, added to the database.
anyways, I am not sure about the if and while combination to satisfy this....
So far I have,
if numeric and satisfies ranges, add to database
else, issue errorC
How can I filter for error A and B?
if ( isset [some code...]) {
$a = ...;
$b = ...);
$c = ...;
if (preg_match('/^\d+$/',$b) && preg_match('/^\d+$/',$c) &&
((1 <= $b && 10 >= $b)) && ((20 <= $c && 30 >= $c))) {
$sql = "INSERT [some code...]
mysql_query($sql);
$_SESSION['success'] = $_POST['success'];
header('Location: index.php') ;
return;
} else {
$_SESSION['error'] = $_POST['error'];
header('Location: index.php') ;
return;
}
}

if (preg_match('/^\d+$/',$b) && preg_match('/^\d+$/',$c)) {
if (($b >= 1 && $b <= 10) && ($c >= 20 && $c <= 30)) {
echo "OK";
} else {
echo "not in range";
}
} else {
echo "not a number";
}

Related

I am getting the wrong result for all ages above 5. I cannot use switch statements

This is the code in question. It seems right to me but it for all ages above 5, it outputs "You can go to preschool"
<?php
$age = 13;
if ($age < 3) {
echo "You are too young for school";
} elseif ($age = 3 or $age = 4) {
echo "You can go to preschool";
} elseif ($age >= 5 and $age < 12) {
echo "You can go to primary school";
} elseif ($age >= 12 and $age < 18) {
echo "You can go to high school";
} else {
echo "You do not have to go to school";
}
?>
You need "==" for compare (just values) $var == $var2 or use "===" for more strict comparation (type and value).
The difference is this
<?php
$var = 1;
$var2 = "1;
echo $var == $var2; //Return 1 (true). Value comparation.
echo $var === $var2; //Return 0 (false). Value and type comparation [int not equal string, but still being 1 == "1"]
So your code should be like this (if age ever will be a int, else use "=="):
<?php
$age = 13;
if ($age < 3) {
echo "You are too young for school";
} elseif ($age === 3 or $age === 4) {
echo "You can go to preschool";
} elseif ($age >= 5 and $age < 12) {
echo "You can go to primary school";
} elseif ($age >= 12 and $age < 18) {
echo "You can go to high school";
} else {
echo "You do not have to go to school";
}
?>
The difference between the loosely == equal operator and the strict === identical operator is exactly explained in the PHP manual.

PHP function inside query wont return value

So, I have a PHP Script that would insert an attendance of the student. First it should check if the attendance with the same student ID and date already exist. If not, it inserts the attendance. I want to insert in the attendance status whether the student is present or late based on my php function compareTime's return value. But the problem is, the function wont return anything. That's why in the attendance data the status column is blank.
function checkAttendance($conn, $stud_id) {
$check = mysqli_query($conn, "SELECT * FROM tbl_attendance WHERE student_id = '$stud_id' AND date = CURDATE()") or die (mysqli_error());
if(mysqli_num_rows($check) > 0) {
return true;
}
else {
return false;
}
}
function compareTime($time,$grade) {
$ctime = strtotime($time);
if($grade == "H1" || $grade == "H2" || $grade == "H3" || $grade == "H4" || $grade == "S1" || $grade == "S2") {
if ($ctime > strtotime('05:00:00') && $ctime < strtotime('07:30:00')) return "P";
else if ($ctime > strtotime('07:30:00') && $ctime < strtotime('8:30:00')) return "L";
}
else {
if($ctime > strtotime('05:00:00') && $ctime < strtotime('07:15:00'))
return "P";
else if ($ctime > strtotime('07:15:00') && $ctime < strtotime('8:30:00'))
return "L";
}
}
function recordAttendance($conn, $sid, $glid, $scid) {
$sql = mysqli_query($conn, "INSERT INTO tbl_attendance(student_id, gradeLevel_id, section_id, date, arrival_time, status) VALUES ('".$sid."', '".$glid."', '".$scid."', CURDATE(), CURTIME(), '".compareTime(date('H:i:s'),$glid)."')") or die(mysqli_error());
}
$res = mysqli_query($connect, "SELECT * FROM tbl_student WHERE card_id = '$cardID'")or die(mysqli_error());
while($row = mysqli_fetch_array($res,MYSQLI_ASSOC)) {
if (checkAttendance($connect, $row['student_id']))
echo "Already Exist!";
else
recordAttendance($connect, $row['student_id'], $row['gradeLevel_id'], $row['section_id']);
}
It could have several reasons actually, but you'll need to debug to see which is the case.
First start debugging by outputting the values of compareTime to see if they actually work at all. If it doesn't, fix that first.
If that works you could try adding a 'hardcoded' value to your query to see if that gets inserted into your (test) data/table. If that doesn't produce a good result either it might be a case of wrong type in the database. Maybe it's expecting an integer or something else?
You could also extract the function call from the query and put it in a variable, it will provide a bit cleaner and more readable code, as well as it being easier to debug.
p.s.
Did you realise that, in the unlikely event of a time being exactly 7:30:00 or 7:15:00, a person falls between the cracks because you only check for greater or smaller than. Some should also be >= or <=
Might be better to rewrite it to something like this:
function compareTime($grade,$time = ''){
$time = (empty($time))?strtotime(date('H:i:s')):strtotime($time);
$time_5 = strtotime('05:00:00');
$time_715 = strtotime('07:15:00');
$time_730 = strtotime('07:30:00');
$time_830 = strtotime('08:30:00');
if ($grade == "H1" || $grade == "H2" || $grade == "H3" || $grade == "H4" || $grade == "S1" || $grade == "S2") {
if (
$time > $time_730
&& $time < $time_830
){
return "L";
} elseif (
$time > $time_5
&& $time <= $time_730
){
return "P";
}
} else {
if (
$time > $time_715
&& $time < $time_830
){
return "L";
} elseif (
$time > $time_5
&& $time <= $time_715
){
return "P";
}
}
}

use OR in if codition to print reverse results in php

I am trying echo result "OK" if ( 1 either both ) variable true, i did so far like this
<?php
$user_id = $_SESSION['user_id'];
$point= "select points from users where id = $user_id "; // in db right now points = 2000
$flag= "select m_boost from users where id = $user_id "; // in db right now flag = 1
?>
<div class="box border">
<div class="box-title">
<?php
if($point < 1000 || $flag = 0) {
echo "not ok";
} else { ?>
echo "ok";
<?php }?>
</div>
it's working if i do like this
if(($point == '2000') || ($flag == '0') ){
but i don't want == operator for $point i want less than < $point < '999'
The problem is :
Keep getting result " Not Ok " even one variable (flag = 1) is true in db
Expected Results:
i want to print "OK" if $point > 1000 or flag == 1,
try this
when you using OR condition you should careful about condition and login. you should implement logic in if condition instead of else.
if($point > 1000 || $flag ==1) {
echo "ok";
}else {
echo 'Not ok'
}
or AS YOU WANT
if($point < 1000 ) {
echo "Not ok";
}else if($flag ==0) {
echo 'Not ok'
}esle {
echo 'ok'
}
or you can use this way
$a=false;
if($point < 1000 ) {
$a=true;
}else if($flag ==0) {
$a=true;
}esle {
$a=false;
}
// you can use this variable in your condition.
if($a) {
echo "ok";
}else {
echo 'Not ok'
}
When you are using OR, if the first condition is met the second is disregarded.
Also, make sure you use double equals (==) for comparison, not single equals (=) which means assignment.
Therefore you want to replace this:
if($point < 1000 || $flag = 0) {
With one of these:
SWAPPED AROUND
if($flag == 0 || $point < 1000) {
or
USING && INSTEAD
if($point < 1000 && $flag == 0) {
Depending on what behaviour you're looking for. It's a little unclear - so any additional clarification from you would be helpful.
Once you get something that you think is working, try to test all possible combinations so that you can be confident it works how you wish.
$flag = 0
You're setting the variable's value to 0.
Example:
$flag = 1;
if($a < $b || $flag = 0){ //$flag's value is 0 now.
...
...
}
In conditions comparisons, the right operator is "==".
if($point < 1000 || $flag == 0) {
List of comparison operators
but i don't want == operator for $point i want less than < $point <
'999'
Didn't fully understood your goals, but maybe:
For checking a value in a range the right logical operator should be "and" (&&);
if($point > 0 && $point < 999){
List of logical operators
Update:
if $point > 1000 or flag == 1
if($point > 1000 || $flag == 1){
echo "ok"
}
if (!$flag && $point < 1000)
{
echo "Not OK";
} else {
echo "OK";
}
Writing this into a truth-table:
flag point result
0 < 1000 Not OK
1 < 1000 OK
0 >=1000 OK
1 >=1000 OK
Worked for me now as per my question
i think we are all here for some contribution reason, flagging down a question is not a way, if you got solution than respond otherwise my question was 100% clear.

if and else statement mixed up

I am doing the following if else statement below but number (//1) and number (//4) get executed at the same time, I am finding it abit hard to understand why.
<?php
//1
if($a == 1 && count($b) == 0) {
// do this
}
//2
elseif ($a == 1 && count($b) > 0) {
// do that
}
//3
if($a== 0 && count($b) == 0) {
// do a different thing
}
//4
else {
// do the last thing
}
?>
I have done this and it works but i think the should be a more suitable way for not using elseif for this.
else if($a== 0 && count($b) > 0) {
// do the last thing
}
but number (//1) and number (//4) get executed at the same time
It's because you don't have else before the if on //3
//3
if($a== 0 &&
Change to elseif($a== 0 &&
At the moment you have two separate IF conditions
You're missing a closing brace after your first if.
Also, you have a weird operator inside your first condition : $$. Maybe you intended to type &&?
$a = 10;
if ($a == 5) {
echo 'ok';
} elseif ($a == 10) { // $a is equal to 10, so it executes;
echo 'not_ok';
}
if ($a > 20) {
echo 'ok_ok';
} else { // $a is not >20 so else statement executes
echo 'not_not';
}
final result: not_oknot_not
If you are performing such tests on one and the same assignee, but different values, you might not want to execute more than one?
I guess you need elseif where third block is if
if ($a == 5) {
echo 'ok';
} elseif ($a == 10) { // $a is equal to 10, so it executes and stops the block;
echo 'not_ok';
} elseif ($a > 20) {
echo 'ok_ok';
} else { // $a is not >20, but the block was stopped on first elseif
echo 'not_not';
}
produces not_ok
Even if you move the else statement after the first elseif block as was suggested
if ($a > 20) {
echo 'ok_ok';
}
will execute, and if it's true, it will produce result, which again will result in double result
You might want to do this...
if ($a == 1 && count($b) == 0) {
// do this
}
//2
elseif ($a == 1 && count($b) > 0) {
// do that
}
elseif ($a== 0 && count($b) == 0) {
// do a different thing
}
else {
// do the last thing
}
The reason they get executed at the same time is that... Well technically they're not executed at the same time since it's procedural, but they both get executed because they are both different if else conditions. If you want only 1 execution, you should combine them :)

How to check for numbers only (including negative)?

how can I check for numbers only from -10 negative to +10 positive?
This is what I have, but I think it's not safe:
if(isset($_POST['number']) && ctype_digit($_POST['number']) && $_POST['number']>=-10 && $_POST['number']<=10){
//do something
}
and the form:
Input a number between -10 and 10: <input type="text" name="number" size="5" />
if( isset($_POST['number'])) {
$num = intval($_POST['number']);
if( $num >= -10 && $num <= 10) {
// do something
}
}
There are other ways, but that one will work. Anything that can't be converted to a number will be treated as zero. If this is not desired behaviour, add:
&& "".$num == $_POST['number']
To that inner IF statement, to ensure that no non-numeric characters were removed from the input.
Check whether a variable is a number including zero and negative values
$x = '-22';
if (isNumber($x, ['zero','negative']))
echo 'Yes';
else
echo 'No';
isNumber($x, $includes=[])
{
if (is_int($x)) {
if ($x === 0) {
if (in_array('zero', $includes))
return true;
} elseif ($x < 0) {
if (in_array('negative', $includes))
return true;
} else
return true;
} elseif (is_string($x)) {
if ($x == '0') {
if (in_array('zero', $includes))
return true;
} elseif ($x[0] == '-') {
if (in_array('negative', $includes))
return ctype_digit(substr($x, 1));
} else
return ctype_digit($x);
}
}

Categories