Comparing issues with values php - php

I have a problem with comparing 2 values and let 1 value change within the if statement. But ofcourse when I reload the page it picks up the first value again. I'm using this code to set some information in a database when a machine is turned on or off.
$urlMachineON = 'http://192.168.0.150/awp/Shredder/PLCfiles/IOmachineActive.html';
// get content
$contentMachineON = file_get_contents($urlMachineON);
//remove first 2 characters
$truncate = substr($contentMachineON, 2);
//remove last 5 characters
$MachineOn = substr($truncate, 0, -5);
//MachineON can only be 1 or 0
$currentState = 2;
if ($MachineOn != $currentState)
{
$stmt = $conn->prepare("INSERT INTO machineactiviteit (Time, MachineStatus) VALUES(NOW(), ?)");
$stmt->bind_param('s', $MachineOn);
if ($stmt->execute() === TRUE)
{
$currentState = $MachineOn;
echo 'success';
}
else
{
echo $conn->error;
}
$stmt->close();
}
elseif($MachineOn == $currentState)
{
echo 'do nothing';
}
So when I do this he will always use the if statement since the $currentState and $MachineOn are always different from each other. In C# you have something like initalize component to set the value one time to a specific value. But I haven't found anything about that in php. So my question is can I set a value only once? Or should I solve this another way?
This is how it should work:
first attempt before: currentState = 2; MachineOn = 0; after: currentState= 0; MachineOn = 0;
second attempt before: currentState= 0; MachineOn = 0; after: currentState= 0; MachineOn = 0;
third attempt before: currentState= 0; MachineOn = 1; after: currentState= 1; MachineOn = 1; (I can change the MachineOn value with a button).

Just save $currentState value somewhere. For example in file or in database.
$currentState = file_get_contents('filepath'); // last saved state (check if is set!)
if($currentState !== $MachineOn) {
file_put_contents('filepath', $MachineOn); // Save current state
} else {
file_put_contents('filepath', 2); // Save other state
}
This is pseoudocode. Remember to check if file exist and has value.

Related

avoid repeating variable due to undefined variable error

I'm trying to make a profile completion progress, which shows the percentage of how much a user has completed his profile settings. If a user has filled in a field, he receives +15 or +5, however, if the field is not filled in he receives +0.
the code I did is really bad, with variable repetitions, I wanted to know if you knew a cleaner way to do this.
if (!empty($user->avatar)) {
$avatar = 15;
} else { $avatar = 0; }
if (!empty($user->copertina)) {
$copertina = 15;
} else { $copertina = 0; }
// dati personali
if (!empty($user->name)) {
$name= 5;
} else { $name = 0; }
if (!empty($user->last_name)) {
$last_name = 5;
} else { $last_name = 0; }
[...]
if (!empty($user->biografia)) {
$biografia = 5;
} else { $biografia = 0; }
$personal = $avatar+$copertina+$name+$last_name+$sesso+$nascita;
$gaming = $steam+$battlenet+$xbox+$playstation+$switch+$uplay+$origin+$ds;
$social = $twitter+$facebook+$biografia;
$punti = $personal+$gaming+$social;
how do I remove all the others {$ variable = 0}?
You can't really, since you want the value to be a number, and not "undefined". You could initialize your variables to 0 like in this answer stackoverflow.com/questions/9651793/….
If you want to get into type comparisons for null variables, check php.net/types.comparisons. I would just initialize the variables to 0 and remove all the else.
OR...
modify your $user object to have all these variables in an array ($key:$value). You can then initialize the array to 0 all over, and modify it. Adding a new profile value would be easy, and adding array values is quick.
This snippet :
if (!empty($user->avatar)) {
$avatar = 15;
}
else {
$avatar = 0;
}
is semantically equivalent to :
$avatar = (bool)$user->avatar * 15;
Explanation:
Non-empty field gets converted to true and empty string or null gets converted to false
Because we do multiplication php true/false values gets converted to 1/0
So after multiplication you get 15 * 1 or 15 * 0 - depending if your field was used or not.

How to set a variable value based on conditions set by other variables

So I am new to PHP, and am currently just doing a little project as practice, I've managed to get down a few lines of code without falling over... but am a bit stuck here.
Essentially, what my script currently does is check three different variables that I have set (each a true/false option) and distinguishes if there is only one true option selected (out of the 3 options, only one can be true, the other 2 must be false). If only 1 value is set to true, the rest of the code runs; if multiple values are set to true, or no values are set to true, it shows an error prompt for the user.
Once this check is done, I wanted to then set the value of $name for example, based on records linked to the relevant variable that is true... This is what I have come up with, but it doesn't seem to work...
if ($value1 == "true") {$name = $result1;}
else if ($value2 == "true") {$name = $result2;}
else if ($value3 == "true") {$name = $result3;}
else exit (0)
So i essentially want to set the $name variable by identifying which of the 3 value variables is true, and then setting $name with the relevant variable retrieved in the $result
Any help would be appreciated. And before anyone goes off on one... I know I may sound a bit mad... but we all have to start somewhere!!
Thanks
It would look much nicer with a switch:
switch(true){
case $value1:
$name = $result1;
break;
case $value2:
$name = $result2;
break;
case $value3:
$name = $result3;
break;
default:
exit();
}
In case you need to make sure only one of the statements is true, validate that prior using this:
//In case you need to make there is only a single true statement
$found = false;
for($i=1; $i<4; $i++) {
$value = "value".$i;
if($$value) {
if($found) {
exit("More than one 'true' statement");
}
$found = true;
}
}
Dracony's answer looks nice indeed, but will fail when multiple values are set to true. For more flexibility, you should consider mapping the values into arrays, and tracking the state (amount of values that are true) with a flag variable. Find a fully commented example that will satisfy all conditions below. Additionally, this code will work with arrays of any length (you can add conditions by simply putting more values in $values and $results).
// store the data in arrays for easier manipulation
$values = array($value1, $value2, $value3);
$results = array($result1, $result2, $result3);
// set a flag to check the state of the condition inside the loop
// it keeps track of the index for which the value is true
$flag = -1;
$name = NULL;
// use for and not foreach so we can easily track index
for ($i = 0; $i < count($values); $i++) {
// if no index has been found 'true' yet, assign the current result.
if ($values[$i] === true) {
if ($flag === -1) {
$flag = $i;
$name = $results[$i];
}
// if a 'true' value has been found for another index
// reset the name var & stop the loop
if ($flag > -1 && $flag !== $i) {
$name = NULL;
break;
}
}
}
if ($name) {
// run code when only 1 value is true
} else {
exit();
}

PHP - better way of checking through variables one by one

I have a php application where users upload specific images, and the number of images can be different per user. I have a variable set on startup as false for each image that i change to true once its done.
For example one user might have to upload 3 and have so far done 2 so:
$required = 3;
$houseImageStatus1 = true;
$houseImageStatus2 = true;
$houseImageStatus3 = false;
Another then may have to upload 5 and have done them all:
$required = 5;
$houseImageStatus1 = true;
$houseImageStatus2 = true;
$houseImageStatus3 = true;
$houseImageStatus4 = true;
$houseImageStatus5 = true;
I need to be able to check that all required images have been uploaded before continuing. At the moment i have a very long-winded and ugly way be doing:
if($required==3){
if($houseImageStatus1==true &&
$houseImageStatus2==true &&
$houseImageStatus3==true){
// allow continue
}
else {
// pause
}
}
if($required==5){
if($houseImageStatus1==true &&
$houseImageStatus2==true &&
$houseImageStatus3==true &&
$houseImageStatus4==true &&
$houseImageStatus5==true){
// allow continue
}
else {
// pause
}
}
Can i do the above but in a much shorter and cleaner way? Maybe in some sort of array and loop through them as a function?
Use arrays for this purposse:
$houseImageStatus[1] = true;
$houseImageStatus[2] = true;
$houseImageStatus[3] = false;
and then check if all are true:
if (count(array_unique($houseImageStatus)) === 1 && $houseImageStatus[0] === true) {
// here you go
} else {
// nope
}
You Could use either:
Array and check for falses in array and by checking the index of array, You could determine the size (here you named it as $required).
OR
Using a counter which increments with each uploading of images....
Use different counters with different users . You dont have to give seperate variables for each user.. You could use any existing user dependant variables like user_id or user_name..
Store the boolean values in an array, use array_filter to remove the false values and then check the array size against your variable $required:
$houseImageStatus = array();
$houseImageStatus[0] = true;
$houseImageStatus[1] = true;
$houseImageStatus[2] = false;
// and so on
if(sizeof(array_filter($houseImageStatus)) == $required){
// everything is okay
}
else{
// something is wrong
}
You can do array with all values set to false:
$houseimages = array();
$n = 5; // How many pictures
for($i = 0; $i < $n; $i++) $houseimages[$i] = false; // Set all to false
And now, when user uploads one picture, just set $houseimages[0] = true; and so on.
Later just look through array and check if all values are true or not.
$required = 3;
$filled =0;
$houseImageStatus1 = true; $filled=$filled+1;
if ($required==$filled){//continue} else {//pause}

Which checkbox is selected and assigning a value

I am trying to create logic to see what checkbox is selected (of 5 possible checkboxes) and if it is selected assign it a value of 0. if it is not selected I was to assign it a value of 1. The proceeding code snippet highlight this but throws a parse error in my else statement and I cannot fighure out why.
//Check to see what checkbox is marked for correct answer
//Correct answer variables
$chkBox1 = 'unchecked';
$chkBox2 = 'unchecked';
$chkBox3 = 'unchecked';
$chkBox4 = 'unchecked';
$chkBox5 = 'unchecked';
if (isset($_POST['chkBox1'])) {
if ($chkBox1 == 'chkBox1Selected') {
$chkBox1 = '0';
}
else{
$chkBox1 = '1';
}
}//End of chkBox1Selected logic
You don't understand how checkboxes work. If a checkbox is deselected before posting, it will not be set on post.
Therefore, the only condition that will ever be present in your code is that every value will show as 1, since they cannot be overridden.
Take this snippet and try it out. It dynamically loops for the amount of variables you need and assigns the values based upon the submitted value.
$_POST['chkBox4'] = 'test';
for( $i = 1; $i <= 5; $i++ )
{
$name = 'chkBox' . $i;
$$name = !isset( $_POST[$name] ) ? 0 : $_POST[$name];
}
print $chkBox2 . ' // '. $chkBox4;
http://codepad.org/51RotnCf
Ok I got it to work from a syntax standpoint, however now no matter what is selected it is still assigning a value of 1 to all the checkboxes and not changing the selected checkbox to a value of 0. Here is the new code that is correct from a syntax standpoint but defaults to 1 no matter what:
//Check to see what checkbox is marked for correct answer
//Correct answer variables
$chkBox1 = '1';
$chkBox2 = '1';
$chkBox3 = '1';
$chkBox4 = '1';
$chkBox5 = '1';
if (isset($_POST['chkBox1'])) {
if ($chkBox1 == 'chkBox1Selected') {
$chkBox1 = '0';
}
}//End of chkBox1Selected logic
if (isset($_POST['chkBox2'])) {
if ($chkBox2 == 'chkBox2Selected') {
$chkBox2 = '0';
}
}//End of chkBox2Selected logic
if (isset($_POST['chkBox3'])) {
if ($chkBox3 == 'chkBox3Selected') {
$chkBox3 = '0';
}
}//End of chkBox3Selected logic
if (isset($_POST['chkBox4'])) {
if ($chkBox4 == 'chkBox4Selected') {
$chkBox4 = '0';
}
}//End of chkBox4Selected logic
if (isset($_POST['chkBox5'])) {
if ($chkBox5 == 'chkBox5Selected') {
$chkBox5 = '0';
}
}//End of chkBox5Selected logic

PHP multiplication weird behavior

I don't know if I have suffered some brain or sight damage, but I can't understand behavior of this code:
$po=1;
$po2=0;
echo $po.'*'.$po2.'=';
if($po*$po2) $po=1;
echo $po;
I'd expect the output to be 1*0=0, but actually it's 1*0=1.
$po is always 1. You initialize it to 1, and later in your if case, you have no else. So it remains 1.
Instead, add an `else:
$po = 1;
$po2 = 0;
echo $po.'*'.$po2.'=';
if ($po * $po2) {
// Unnecessary - it's already 1
$po = 1;
}
// Set it to 0...
else {
$po = 0;
}
echo $po;

Categories