Strange Boolean Reaction - php

$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']);

Related

How to add integers to a PHP variable

I'm trying to create a sorting algorithm based off a query. Essentially the user would input values for Height, Weight, and a few other attributes. I am then querying our database of models to match that person with someone who has the closest measurements to those that the user inputted. I'm trying to do this based off a weighted variable that I am assigning within the "while" statement of the query and then returning that variable's value at the end. Here is some code to show you what I mean:
$userHeight=$_POST['height'];
$userWeight=$_POST['weight'];
$userShoulder=$_POST['shoulder'];
$userWaist=$_POST['waist'];
$userInseam=$_POST['inseam'];
$heightMatchMultiple=0;
$heightMatchMultiple=0;
$weightMatchMultiple=0;
$shoulderMatchMultiple=0;
$waistMatchMultiple=0;
$inseamMatchMultiple=0;
function matchValues($array){
if(mysqli_num_rows($array) > 0) {
while($row=mysqli_fetch_array($array)){
$heightMatchMultiple=0;
if(isset($row['modelHeight'])){
if($userHeight==$row['modelHeight']){
$heightMatchMultiple=10;
}
elseif($userHeight==$row['modelHeight']+1 || $userHeight==$row['modelHeight']-1){
$heightMatchMultiple=9;
}
elseif($userHeight==$row['modelHeight']+2 || $userHeight==$row['modelHeight']-2){
$heightMatchMultiple=8;
}
elseif($userHeight==$row['modelHeight']+3 || $userHeight==$row['modelHeight']-3){
$heightMatchMultiple=7;
}
else{
$heightMatchMultiple=1;
}
}
echo "Model Match Multiple: " . $heightMatchMultiple . "<br>";
}
}//end of if num rows
else {
echo "No results to display.";
}
}//end of function
When I run this function, it is returning the else statement's value for heightMatchMultiple of 1 instead of 10 because there is a model in the database with a height of 69 which is what I used as user input.
Can I add +1 or +2 directly to the $row['modelHeight'] variable as I did or is there a better way to do this.
EDIT:
Some people were asking where I initialized the variable $userHeight so i added it to the code. I tried creating global variables for $heightMatchMultiple=0 as a way to make those variables usable within my matchValues function. Is this correct?
Where is $userHeight being initialized/passed in? I think the reason you're currently getting 69 is because $userHeight has not been set, hence it gets a value of zero by default, which means that 1 will be the correct answer if $row['modelHeight'] is 69.
To answer your real question, which is really about order of operations: yes, what you have written should do what I believe you are trying to achieve. However, you should probably add parenthesis, even though they aren't strictly necessary, just as a hint to your future self that you really did intend for the calculations to happen in a certain order.
For example, instead of this:
elseif($userHeight == $row[ 'modelHeight' ] + 1 || $userHeight == $row[ 'modelHeight' ] - 1)
you could write this:
elseif(($userHeight == ( $row[ 'modelHeight' ] + 1 )) || ( $userHeight == ( $row[ 'modelHeight' ] - 1)))
Or you could re-write each of the checks using abs() like this:
elseif(abs($userHeight - $row['modelHeight']) == 1 )
This is arguably more descriptive, since what you're really trying to say is "if the difference is 1".
But yes, you can use the + 1 and +2 etc as in your original code, but you do need to set or pass in the $userHeight variable at some point.

My If statement is not compare with mysql data?

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.

TINYINT (0, 1) for boolean values in MySQL

as the title states ,TINYINT (0, 1) for boolean values in MySQL return true and false value ,,but i want yes and no value when i retrieve TINYINT (0, 1) values from database. is it possible??
Use IF:
SELECT IF(bool_value, 'yes', 'no') as string_value...
tinyint doesnt return true or false. It returns 0 or 1. If you want yes and no, you need to specify that yourself:
if($return == 0) {
return "no";
} else {
return "yes";
}
Yes, it is possible. One way is to add CASE to it:
SELECT
CASE
WHEN value = true THEN 'yes'
ELSE 'no'
END
FROM
`table`;
Another one, as Max suggested, add IF option.
Wanting "yes" and "no" sounds like it's for display purposes, and how you choose to format data from your database/models for display should be in your view oriented code and not the database schema nor the query logic, though there are valid exceptions to the latter. Aside from considerations such as whether "first name" and "last name" as separate items could be useful rather than a single "name" field, decisions about database structure should be based on what you need to store and how different data items relate to each other, not on how data is going to look once retrieved. Particularly as you're using a framework, this should be straightforward.
That said, you could use an enum type instead, defining the enum as enum('no','yes'), though cake may still not have support for enums. You can then get and set string values or numeric ones (1 and 2, or subtract 1 to get 0 and 1). Overall though, tinyint with values 0 and 1 is probably preferable as it's conventional and less likely to lead to mistakes/bugs now or in the future.
Use AppModel::afterFind
http://book.cakephp.org/2.0/en/models/callback-methods.html#afterfind
public function afterFind($results, $primary = false) {
foreach ($results as $index => $row) {
if (isset($row[$this->alias]['yes_or_no'])) {
$results[$index][$this->alias]['yes_or_no'] = $row[$this->alias]['yes_or_no'] ? 'yes' : 'no';
}
}
return $results;
}

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
}

Determine if variable has ANY text

I would like to determine whether or not a variable has any text at all.
For instance, my current code is this:
if (is_numeric ($id))
{
//do stuff
}
else
{
// do other stuff
}
However, there is a problem if my variable contains both a string and a number
such as "you are 93 years old",
because it sees that number 93 is present and considers the variable numeric.
I want the if statement to only "do stuff" if there is absolutely no text in the variable at all.
Thanks
Try casting the value to int (or float) then compare it back to the unaltered version. They should match values (but not type)
if((int)$id == $id) {
} else {
}
another option would be to use preg_match("/^([\d.\-]+)$/", $id). This would allow you to be very specific about what characters you let $id contain. However using regexp should be considered as the final choice (for performance reasons)
if(empty($var) && $var !== "0" && $var !== 0) {
// it's really empty, not a string "0" and not a numeric 0
}
You could also check if it's not a boolean false for the sake of completeness.

Categories