My If statement is not compare with mysql data? - php

Halo, I got a If statement here but is not working.
The system just pass me to the last page which I set it.
And that is not what I want.
What I want here is when the user login, the system automatic check the user belong to which department and send them to the correct page.
$departmentsql="SELECT department FROM staff_table";
$departmentsqlresult=mysql_query($departmentsql);
$departmentcount=mysql_num_rows($departmentsqlresult);
if($departmentcount == "A"){
header("location:departmentA.php");
}
else if($departmentcount == "B"){
header("location:departmentB.php");
}
else if ($departmentcount == "C"){
header("location:departmentC.php")
}
The system just send me to the departmentC.php every time, no matter which user I login.
And that is not what I want.
Can anyone tell me whats wrong with my code?
Appreciate for your answer. Thanks

You have 2 errors :
if($departmentcount == "A"){
header("location:departmentA.php");
}
>> $departmentcount will contain a numric value
PHP doesn't implictyly typecast, so when you compare 2 values, it treats both of them of same type.
On comparison, since you are comparing $departmentcount with a char, it'll expect $departmentcount to contain char value too, which is not the case...so condition becomes false for all of your if and elseif, hence no output
Compare it like
if($departmentcount == 10) //compare with number
>> when you'll compare successfully, header wont redirect, because your syntax for header is also incorrect
Correct it this way :
header("Location: departmentA.php");
/* you need a ^^ space here */

First you do not seem to be taking the logged in user and doing a lookup that way, it seems currently you would return all departments regardless of the user who has logged in.
Next mysql_num_rows returns the number of rows returned in that query you would need mysql_fetch_row, mysql_fetch_object etc

You did mistake use mysql_fetch_array
$departmentsql="SELECT department FROM staff_table";
$departmentsqlresult=mysql_query($departmentsql);
$departmentcount=mysql_fetch_array($departmentsqlresult);
if($departmentcount[0] == "A"){
header("location:departmentA.php");
}
else if($departmentcount[0] == "B"){
header("location:departmentB.php");
}
else if ($departmentcount[0] == "C"){
header("location:departmentC.php")
}

First you have to check what's the basic difference between mysql_num_rows and mysql_fetch_array . As suggested by other it will works fine.
If still you facing issue then to use "===". comparing values in php.

Related

PHP If (!isset(...) || !isset(...))

I'm trying to check if the first $_COOKIE['one'] exists OR the second $_COOKIE['two'] exists and if none exists to redirect the user.
Only one of those two cookies are going to exist when this script is running.
if (!isset($_COOKIE['one']) || !isset($_COOKIE['two'])) {
header('Location: ./');
} else {
...
}
I tried many things but every time I get into this if altough one of those cookies always exist.
This is a simple case of inverted logic. As Mark pointed out, you need to be using the boolean && (AND) operator. You are trying to see if both don't exist, then send the header. Currently, if either exists, you send the header anyway.
Just change if (!isset($_COOKIE['one']) || !isset($_COOKIE['two'])) {
to
if (!isset($_COOKIE['one']) && !isset($_COOKIE['two'])) {
Or (||) returns true if either the left or right of the statement is true. And (&&) returns true only if both parts of the statement are true. The Not(!) operator reverses true->false and false-> true.
isset tells you if the cookie exists. If the cookie exists, it returns true. You are correct in using not on this, as you want it to tell you if the cookie doesn't exist (opposite). However, you only want to send the header if BOTH cookies don't exist. Or will send it if one doesn't exist.
You wrote an opposite logic to what you really want.
You said that
You're trying to check if
That's an if conditional.
the first $_COOKIE['one'] exists
For that you use isset, which you did and it's right.
OR the second $_COOKIE['two'] exists
So you'd use the OR operator ( || )
and if none exists to redirect the user.
That's an else, and then use header to redirect.
Converting your words to literal code, you'd have this:
if (isset($_COOKIE['one']) || isset($_COOKIE['two'])) {
//... Do your thing
} else {
header('Location: ./');
}
Your code also works with the fix provided by Mark in the comments, but might confuse you in the future...
You can also do this to avoid nesting:
if (!(isset($_COOKIE['one']) || isset($_COOKIE['two']))) {
{
header('Location: ./'); exit;
}
//... Do your thing
If only one of the cookies will ever be set then then your if condition will always be true so the redirect will happen.
Change || for &&,
if (!isset($_COOKIE['one']) && !isset($_COOKIE['two'])) {
header('Location: ./');
} else {
//
}
More elegantly, isset() can handle muliple arguments and negating its return value will give you exactly what you want.
Code: (Demo)
var_export(!isset($cookie1, $cookie2)); // Are either missing? Yes, both are missing.
echo "\n";
$cookie1 = 'declared';
var_export(!isset($cookie1, $cookie2)); // Are either missing? Yes, one is missing.
echo "\n";
$cookie2 = 'declared';
var_export(!isset($cookie1, $cookie2)); // Are either missing? No, neither are missing.
Output:
true
true
false

cakephp2 beginner: how to compare the data from the db with a integer?

I want to compare a data from the db in cakephp2.
For example I have a data $product['price'], this data contains a value of 0.
I want to compare it with integers like the source code below, however,I cannot compare them.
I would love to have some help.
if($product['price']==0){
echo "free";
}else{
echo "$".$product['price'];
}
Since your var_dump of $product['price'] shows it is a string you need to convert it to an integer first - use
if (intval($product['price']) == 0) {
//do something
}
else {
//do something else
}
If possible though, it would be better to change your actual database so that the field you're looking at is an integer to begin with (stops someone saving a price as "SomeRandomLetters" instead ;)

Modulus of a string

I am in a very puzzling situation. Intially when an user visits a particular page, a popup is shown. User can accept it or decline it. When a user declines it, after 5 page visits, the pop up is again shown to user. This part is working perfectly. When user clicks ok, an ajax call is made and the SESSION variable is set to ok. Lets say initially $_SESSION['count'] = 0. I have two condition statements.
if($_SESSION['count']%5 === 0)
{ // do something
}
elseif($_SESSION['count'] === "ok")
{ // do something
}
Now when an user press ok, an ajax call is made updating $_SESSION['count'] = "ok".
When the user again reloads the page, condition if($_SESSION['count']%5 === 0) gets true even though $_SESSION['count'] is now ok. Later after much experimenting, i came to know that in php i am able to divide or find modulus string by number which will result in zero. How can i handle this?
You can use is_numeric to check if it is a count or 'ok'
http://php.net/manual/en/function.is-numeric.php
if(is_numeric($_SESSION['count']) && $_SESSION['count']%5 === 0)
{ // do something
}
elseif($_SESSION['count'] === "ok")
{ // do something
}
Though generally, I would set ok to be the value of a different variable in $_SESSION as a best practice. If I was looking at the code I would find it very odd to see something called count having a string value.
PHP is very good at implicit casting.
A solution to your issue is simply re-arrange your if else tree.
if($_SESSION['count'] === "ok")
{
// do something
}
elseif($_SESSION['count'] % 5 === 0)
{
// do something
}
Readability
Something to bare in mind, is that a variable count should really contain a value. Perhaps using a different variable might make your code a little less confusing to a reader.
In php, (int) "some string" == 0, so check if $_SESSION['count'] is an integer (e.g. using is_numeric()) before doing the modulus.
Check this working example. It may help:
if(!isset($_SESSION['foo'])) {
$_SESSION['foo'] = 0;
} else {
$_SESSION['foo']++;
}
var_dump($_SESSION['foo']%3);
if(is_numeric($_SESSION['count']) AND $_SESSION['count']%5 === 0)
{ // do something
}
elseif($_SESSION['count'] === "ok")
{ // do something
}

PHP Multiple condition if statement returning nothing

I have been trying to figure this out for weeks, it is a simple statement yet it never executes the if statement. I'm echoing the variables to the screen so I know they exist and each condition is true, but the echo "something" never executes.
if ($db_a==$session_a && $db_b==$session_b && $dbfreq_b=="1")
{
echo "something";
}
I thought it was just the brackets as I had this originally:
if (($db_a==$session_a) && ($db_b==$session_b) && ($dbfreq_b=="1"))
I am comparing variables stored in a MYSQL database with session variables.
If I use Var_dump the db variables are null, yet they echo the expected string value to the screen.
$db_a="username";
$session_a="username";
$db_b=="keyword string"; -mostly one word but could be multiple
$session_b=="keyword string";
$dbfreq_b="1"; - This is the frequency that the keyword appears in the MYSQL database
using vardump $db_a and $db_b are NULL yet they echo what I am expecting to see to the browser.
Hopefully this explains things a bit more?
Thank you for the very prompt help!!
If as you say $db_a = $session_a AND $db_b = $session_b AND $dbfreq_b = 1 then it's impossible that condition returns false.
Please check your code again (all 5 variables) and make sure ALL of the conditions are met.
You could just split your single IF into three separate conditions so that you know which one returns false.
if ($db_a == $session_a) {
echo "first OK\n;"
}
if ($db_b == $session_b) {
echo "second OK\n";
}
if ($dbfreq_b == "1") {
echo "third OK";
}
Could you add the values of your variables to your question?

Strange Boolean Reaction

$alerter2="false";
for ( $counter = 0; $counter <= count($filter); $counter++) {
$questionsubmitted=strtolower($_POST[question]);
$currentcheck =$filter[$counter];
$foundvalue=stripos((string)$questionsubmitted,(string)$currentcheck);
echo $foundvalue;
if ($foundvalue==0) {
$alerter2="true";
} else { }
}
if (!($alerter2=="true")) {
$sql="INSERT INTO Persons (Name, Email, Question)
VALUES
('$_POST[name]','$_POST[email]','$_POST[question]')";
} else {
echo "Please only post appropriate questions";
}
For some reason, whenever I run this, stripos returns 0 every time for every iteration. It's supposed to be a filter, and using echo I found that stripos is 0 every time that it appears. However, when I use 0 in the if, it returns true for even those that don't have the word in them.
Where should I use mysql_real_escape_string? After the query? Note, I am making this a piece of code where I want user input to be saved to a database.
stripos return false if the value is not found, or 0 if it is the first character. Problem is, php automatically cast boolean to the 0 integer or the 0 integer to false. So I think a cast is happening here and thus the condition don't do what you want.
You can use === to also check the type of the variable :
if ($foundvalue === 0) {
$alerter2="true";
}
There's more details about this problem in the linked documentation for stripos.
You should also remove the empty else clause for a cleaner code and use mysql_real_escape_string to sanitize the values before putting them in your database.
You need to change
if ($foundvalue==0)
to
if ($foundvalue===0) // three equals signs
or something equivalent, depending on your logic (I didn't quite understand what's going on).
But as everyone says, THIS CODE IS OPEN TO SQL INJECTION ATTACKS (among other problems).
Also,
$questionsubmitted=strtolower($_POST[question]);
should probably be:
$questionsubmitted=strtolower($_POST['question']);

Categories