PHP if statement does not work [closed] - php

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 8 years ago.
Improve this question
I have written a code where a value is got from mysql and if it is 1 then row should be in red colour and if it is 0 the row should be in green colour. When I execute the code it always goes to the else statement.
Code is as below:
while ($row = mysqli_fetch_array($result))
{
$bprofit=$row['profit_loss'];
if ($bprofit == "1") {
$colour='#FF0000';
} else {
$colour='#31B404';
}
echo "<tr bgcolor=$colour>";
echo "<td>" . $bprofit . "</td>";
}
and output is:
1
0
0
all in green colour only.
Any suggestions?

You have an extra p in $bpprofit:
if ($bprofit == "1")

change if ($bpprofit == "1") to if ($bprofit == "1")

In addition to the misspelling mentioned in other answers, I think you need to reference the first index of the array like so:
if ($bprofit[0] == "1") ...
EDIT
Based on your new code, are you sure the value that is being returned is a string and not numeric? If it is numeric, you would want your if statement to look like this:
if ($bprofit == 1) ...

In situations like this it never hurts to use var_dump() function and see what the variable actually contains and how you need to access it.

When encountering problems such as the one above, try activating error reporting in PHP. One way to do this is to update php.ini, but since this might affect other projects in which you don't want error reporting, it might be better to activate it when needed.
What's important is that you enable reporting of notices, since they'll appear when you use a variable that hasn't been set.
The code below is a simple example:
<?php error_reporting(E_ALL);
if ($undefined == 1) {
// do stuff
}
When this page is displayed, a notice will be shown:
Notice: Undefined variable: undefined in
/var/www/test/undefined_example.php on line 3
Of course, this might not be a suitable solution for all problems, but it might help you figure out where to look.
It might also make you a better programmer; by "reminding" you to declare variables with a standard value if they are not always assigned before later use.

Related

Check for null in an if loop [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 4 years ago.
Improve this question
I am having some problems with my program.
I am creating a script which displays all the properties in the properties table in our database and one row in the table should show available or sold. it should check if the puserId is null or 1 or more
//Execute the Query
$records = mysqli_query($con, $sql);
while($row = mysqli_fetch_array($records)){
echo "<tr>";
echo "<td>".$row['propertyId']."</td>";
echo "<td>".$row['propNum']."</td>";
echo "<td>".$row['AptNum']."</td>";
echo "<td>".$row['street']."</td>";
if (empty(['puserId'])) {
$status = 'Available';
}else {
$status = 'Sold';
}
echo "<td>".$status."</td>";
When i use this it shows that all properties are sold, also the ones wich have a puserId of null. It doesn't give me any errors though.
Anybody knows how I should do this?
Thanks in advance :)
Replace:
if (empty(['puserId'])) {
with:
if (empty($row['puserId'])) {
in order to fix the missing variable $row typo (your actual code checks whether the array ['puserId'] is null, which is obviously false) . If your field is either null or numeric, you can also write that as:
if (is_null($row['puserId'])) {
but my advice is to avoid using empty/null values in table fields related to identifiers. Just give them a default value of 0 to make everything easier. At that point you could write your check as:
if ($row['puserId'] == 0) {
Other than the $row['puserId'] typo, empty doesn't really look useful there. It includes an isset check that is pointless considering you know that column exists. You aren't checking that any of the other columns are set before you use them. There's really no need to check that one either. Just evaluate it directly. null or 0 values will evaluate as false in the if condition..
if ($row['puserId']) {
$status = 'Sold';
} else {
$status = 'Available';
}

how do you update a row in mysql with php from a user [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 6 years ago.
Improve this question
$pos = $_POST['pos'];
$played = $_POST['played'];
$won = $_POST['won'];
$drawn = $_POST['drawn'];
$lost = $_POST['lost'];
$goalsfor = $_POST['goalsfor'];
$goalsag = $_POST['goalsag'];
$goaldif = $_POST['goalsdif'];
$points = $_POST['points'];
if (mysqli_query($db,"UPDATE division2 SET Pos ='".$pos."', played ='".$played."', won ='".$won."', drawn ='".$drawn."', lost ='".$lost."', goalsfor ='".$goalsfor."', goalsag ='".$goalsag."', goalsdif ='".$goaldif."', points ='".$points."', WHERE team = Treaty Celtic") === true) {
echo '<script language="javascript">';
echo 'alert("Row Successfully Inserted")';
echo '</script>';
include("index.html");
This is what i have so far but i keep getting "error inserting row"
I want to update the entire row from a user input using $_Post in php.
WHERE team = Treaty Celtic is one of the problems here.
That needs to be wrapped in quotes, since we're dealing with a string.
WHERE team = 'Treaty Celtic'
Those 2 syntax errors would have been caught had you checked for errors.
Read up on string literals:
http://dev.mysql.com/doc/en/string-literals.html
and checking for errors would have thrown you a syntax error about it.
http://php.net/manual/en/mysqli.error.php
and a trailing comma in
points ='".$points."', <<< THERE
Remove it.
Also make sure those POST arrays have values with their respective name attributes in the HTML form.
Add error reporting to the top of your file(s) which will help find errors.
<?php
error_reporting(E_ALL);
ini_set('display_errors', 1);
// Then the rest of your code
Sidenote: Displaying errors should only be done in staging, and never production.
Add or die(mysqli_error($db)) to mysqli_query().
Or as an else to the if:
else {
echo "Error: " . mysqli_error($db);
}
Seeing now that it's not working for you, make sure that you are using the same MySQL API as your query, being mysqli_.
Different APIs do not intermix.
And as bonus:
Your present code is open to SQL injection. Use mysqli_* with prepared statements, or PDO with prepared statements.
I found two errors in your query additional , at the end of field list and missing ' in where condition. Update it to following:
if (mysqli_query($db,"UPDATE division2 SET Pos ='".$pos."', played ='".$played."', won ='".$won."', drawn ='".$drawn."', lost ='".$lost."', goalsfor ='".$goalsfor."', goalsag ='".$goalsag."', goalsdif ='".$goaldif."', points ='".$points."' WHERE team = 'Treaty Celtic'") === true) {
You need to make sure that a POST has been sent from the user form. Use the if (!empty($_POST)){...} to confirm whether the post has happened or Not. Move your entire block code to the if block.
if (!empty($_POST)){
//your entire code here...
}else{
echo "No POST !!!";
}
May be there is some columns with NOT NULL attribute which caused the error... Good Luck..

$_GET["id"] don't respond [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 7 years ago.
Improve this question
I am a beginner in php , and i want make a test with GET .
I want display , for example "ok" on my php page if my id parameter is 1 but i have always 1 when i change the id parameter to another value .
Details :
when i make this url :
http://localhost:81/test/testajax.php?id=2
expected result :
not ok
obtained result :
ok
testajax.php
<?php
if($_GET["id"] = 1)
{
die('ok');
}
else
{
die('not ok');
}
?>
One equal sign (=) sets the value of a variable. $foo = "bar"; would set $foo to store bar.
You want to use two equal signs (==), which is a comparison operator. ($foo == "bar") would check to see if $foo is equal to bar.
You can check the different types of operators at http://php.net/manual/en/language.operators.php
May be you should go through this basics before you start.
you should put two equal signs to compare.
if($_GET["id"]==1)
correct code:
<?php
if($_GET["id"] == 1)
{
die('ok');
}
else
{
die('not ok');
}
?>
As you are setting the variable, the if statement is always equating to true
Just thought it was worth Noting this as that is the logical reason for your issue

What is a better way to write an if statement using PHP [closed]

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 8 years ago.
Improve this question
I have a option dropdown where I need to echo selected if a value is equal to the search variable.
Right now I am using PHP if statements to decide this, but I would like clean it up a little by using a method that doesn't take up so many lines in my code.
Here is an example of my php if statement:
<option value="antiques" <?php if($_POST['category'] == 'antiques'){echo 'selected';}?>>Antiques</option>
While this works, it just takes up quite a bit of space in my code as I have close to 100 of these selection options.
Is there a better way to check if a post variable is equal to the value of this option and then echo selected?
A simple way to do this is using the PHP ternary operator (more info available here: http://php.net/manual/en/language.operators.comparison.php [scroll down below the big warning about floats])
<option value="antiques"<?php echo ($_POST['category'] == 'antiques')?' selected':'';}?>>Antiques</option>
It doesn't save much room in this instance, but it is a cleaner way to write it inline with HTML in my opinion.
Edit with code from #crazymoin
The idea of moving it into a function is great to make it easy too.
I would modify the function like this:
function abc($post,$value,$label){
echo '<option value="'.$value.'"'.($_POST[$post] == $value)?' selected':''.'>'.$label.'</option>';
}
Then you can call it with this:
<?php abc('category','antiques','Antiques'); ?>
Note that if for some reason the specified index in the $_POST array doesn't exist, PHP will throw some warnings about an undefined index. You may want to expand the function to do some checking with isset(), etc. as well.
create a function and use it as many times you want:
function abc($postData, $thisData) { if($postData == $thisData) { echo ' selected';} }
Now do this:
<option value="antiques" <?php abc($_POST['category'], 'antiques'); ?> >Antiques</option>
hope it help!
Change using Justin Turner response:
Function is:
function abc($postData, $thisData) {
echo '<option value="'.$thisData.'">'.($_POST['category'] == 'antiques')?' selected':''.$thisData.'</option>';
}
Now just use the function as many times you want:
<?php abc($_POST['category'], 'antiques'); ?>
I like doing all my logic processing in one area of the code.
A clean way to do this would be to create an array with all the categories. Then fill in the one matching the category with selected. In each menu option, print out the contents of the array key matching the name of the option.
<?php
$selected=array(
'antiques'=>'',
'horses'=>'',
'umbrellas'=>''
);
$selected[$_POST['category']]='selected';
?>
<option value="antiques" <?php echo $selected['antiques'];?>>Antiques</option>

Un-Definded variable error when not logged on. [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 8 years ago.
Improve this question
I've an error stating "Notice: Undefined variable: user_data" only when no one is logged in, when someone is logged in, it says Hello (Users name)
Here is the piece of code that echos the name
"Hello, <?php echo $user_data['first_name']; ?>!"
Is there anyway that it can just say hello, when no user is logged in, instead of the error message.
Thanks.
Check if variable exists before using it,
$username = isset($user_data['first_name']) ? $user_data['first_name'] : "";
echo "Hello ".$username ."!";
Yes, just:
Hello <?php echo isset($user_data['first_name']) ? ", ".$user_data['first_name']: ''; ?>!
I feel like the previous answers do not really explain what is happening, so I'll try to be more elaborate here.
What both of them do is make use of a ternary operator, which I like to refer to as an "immediate if", you can think of it as the following snippet on one line:
if ($condition) {
echo "this";
} else {
echo "that";
}
or, with the ternary operator:
echo $condition ? "this" : "that"; // prints this if condition is true, that if false.
What you really need to solve your problem, is check if your variable is set with isset, isset checks if a variable is set, so using that in an if condition, will you solve your error.
Example, and also the answer to your question:
if (isset($user_data['first_name'])) {
echo 'Hello, ' . $user_data['first_name'];
} else {
echo 'Hello!';
}
So while the ternary operator is more convienient to use here, it is not required to solve your problem, only isset in a check to verify it is set, is required.
That said, both of them do solve your problem, it's just less readable, and may be a little bit confusing.

Categories