How to add integers to a PHP variable - php

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.

Related

Using for loop within if statement in PHP

I am writing a rostering app. This statement checks that by booking an extra shift the user doesn't violate a rule whereby they have booked more than 7 night shifts in a row. This code runs fine but I am trying to find a more elegant way to write it, for instance using a for loop within the if statement. This snippet exists within a bigger while loop.
if (
$original_shift->night_shift==true &&
$p_lookback_night_7===[1,1,1,1,1,1,1] || $p_lookforward_night_7===[1,1,1,1,1,1,1] ||
($p_lookback_night_1===[1] && $p_lookforward_night_6===[1,1,1,1,1,1]) ||
($p_lookback_night_2===[1,1] && $p_lookforward_night_5===[1,1,1,1,1]) ||
($p_lookback_night_3===[1,1,1] && $p_lookforward_night_4===[1,1,1,1]) ||
($p_lookback_night_4===[1,1,1,1] && $p_lookforward_night_3===[1,1,1]) ||
($p_lookback_night_5===[1,1,1,1,1] && $p_lookforward_night_2===[1,1]) ||
($p_lookback_night_6===[1,1,1,1,1,1] && $p_lookforward_night_1===[1])
) {
return 'You can\'t do more than 7 night shifts in a row';
break;
}
The $p_look variables get populated by a loop looking either back of forward the specified number of days at the end of the variable name and returning an array of true or false for that number of days dependent on whether those are night shifts or not.
As an alternative to building several arrays and complex comparisons, this alternative just uses 2 arrays, one with the days prior and one looking forward. I'm not 100% sure if this includes the day they are trying to book off, but hopefully the idea is easy enough to adjust to your needs.
The basic concept is to look backwards through the $p_lookback_night list and count the 1's, stopping when it reaches a 0. It then does a similar thing through the $p_lookforward_night list. The end result is the number of 1's in a row...
$p_lookback_night = [0,0,0,0,1,1];
$p_lookforward_night = [1,1,1,1,0,0];
$run = 0;
foreach (array_reverse($p_lookback_night) as $test ) {
if ( $test == 1 ) {
$run++;
}
else {
break;
}
}
foreach ($p_lookforward_night as $test ) {
if ( $test == 1 ) {
$run++;
}
else {
break;
}
}
echo $run;
With the test data it gives 6, so you can use this to decide if they are trying to book 7 in a row.
Assuming all those arrays can only contain 1 in this case you can simply just count the values
&& count($p_lookback_night_7)===7 || ...
Maybe even use the int at the end dynamically but this will be probably more trouble that it is worth. Something like
for($i=1;$i<8;$i++){
if(count(${"p_lookback_night_".$i}) == $i && count(${"p_lookforward_night_".$i}) == $i ){
..wahtever
}
}

Local/Global vars in PHP

I'm a newb. I have several tables to store forms and I want the next user's input to be stored the table with the least responses (each form is different).
I've taken the rowcounts from the sql db and they are working. I use the code below detect how many responses there are and hence set $testnumber accordingly.
The code fails. Essentially, when I echo $testnumber, it doesn't matter what values the row counts are, it just randomises according to the first if statement.
When I delete the first if statement, I get an error saying that $testnumber is undefined regardless of the values of rowcounts.
I am absolutely confused the hell out. In my head the var $testnumber is local in all of the statements (they are not defined elsewhere) so they should all either work or not work.
I would appreciate some help. I know my if statements are crap and doesn't cover all cases so any help here would be useful but most IMPORTANTLY can you explain why my other statements are being ignored and why the first one isnt?
Thank you
if ($rowcount1 = $rowcount2 = $rowcount3 = $rowcount4){ // if all rowcounts are equal
$testnumber = mt_rand(1,4);
}
if ($rowcount1 < $rowcount2){ //rowcount for 1 is lowest
if($rowcount1 < $rowcount3){
if($rowcount1 < $rowcount4){
$testnumber = 1;
}
}
};
if ($rowcount2 < $rowcount1){ // rowcount for 2 is lowest
if($rowcount2 < $rowcount3){
if($rowcount2 < $rowcount4){
$testnumber = 2;
}
}
};
if ($rowcount3 < $rowcount1){ // rowcount for 3 is lowest
if($rowcount3 < $rowcount2){
if($rowcount3 < $rowcount4){
$testnumber = 3;
}
}
};
if ($rowcount4 < $rowcount1){ //rowcount for exp2 is lowest
if ($rowcount4 < $rowcount2){
if ($rowcount4 < $rowcount3){
$testnumber = 4;
}
}
};
echo "Final Testnumber: " . $testnumber;
Your first comparison statement isn't a comparison at all: single = sets a variable, double == tests for equality. Thus, your conditional will always evaluate to TRUE, because it's setting your variables correctly.
On top of that, you need to expand out your statements, as equality comparisons don't work this way in PHP.
if (($rowcount1 == $rowcount2) && ($rowcount2 == $rowcount3) && ($rowcount3 == $rowcount4)){ // if all rowcounts are actaully equal
Check out the relevant PHP docs: Assignment Operators, Comparison Operators
Edit: Your next conditional statements are hampered by the fact that it appears you're running into issues with Variable Scope. Basically, in order to access the $testnumber variable, you'll need to define it outside the "scope" of a conditional block.
$testnumber = 0;
if (($rowcount1 == ...
While outside the scope of the question: based on what you've provided here, it may be worthwhile to check out the PHP documentation on arrays, it will help you immensely as you start to scale your code up.

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.

Check in array if only one specific entry is present

I am trying to check if there is only one value in an array and if that specific value is "Home" then do something. Is the method below the best way to accomplish this or can I do it in one step?
Like:
$mymenu; // array
if(count($mymenu) < 2 && in_array('Home', $mymenu)){
// Do something
}
The only other changes I'd make would be:
if(count($mymenu) === 1 && $mymenu[0] === 'Home')
Changing the count check from < 2 to === 1 reads better to me; it makes more sense when reading the code back, since it conveys what you actually mean.
As for in_array, since you know there should only be one item in your array, it's probably faster to just use $mymenu[0] instead of doing a needle/haystack lookup.
Other than that, there isn't a more concise way to do what you want.
Try this ternary Operator ...
echo count($mymenu) === 1 && $mymenu[0] === 'Home' ? 'Do something' : null;

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