Why is my if statement not working the way I expect? - php

I am trying to achieve the following: I ask my SQL database a query using SELECT * FROM subjects. After doing that I ask for the array using mysqli_fetch_assoc. Until that point all is fine. The problem now is that when I try to modify in each loop the value of $genero depending if it's 1 or 0. But the value of $genero never changes, it's always 1 and I am sure that the array is fetching 0 and 1. Any idea while the values of $genero are not changing through the loop?
while ($subject = mysqli_fetch_assoc($result)) {
if ($subject["sexo"] = 1) {
$genero = "<img src='images/hombre.png' />";
} else {
$genero = "<img src='images/mujer.png' />";
}
echo $genero;
}

Your comparison operator is wrong. You're using = which is an assignment operator. In your example it will always be true. You need to use == which is a comparison operator.
if ($subject["sexo"] = 1) {
should be
if ($subject["sexo"] == 1) {

In if statement you should use double equal sign: if (a == b)

Related

variables changing during IF loop

I'm working on a PHP script to make a catalog. The relevant columns in my database are Vid, banner, category and Scategory. Vid is the primary key, banner is the path to my img files, and category and Scategory are both numbers for the their respective ID. Everything is over simplified as I'm just testing the scripts. There is currently 20 records in the table.
<html>
<head>
<style type="text/css">
</style>
</head>
<body>
<?php
require "config.php";
$sql = "SELECT Vid,banner,category,Scategory FROM display";
$result = $conn->query($sql);
$row = $result;
$min = 10;
$max = 20;
while ($row = mysqli_fetch_assoc($result)) {
implode ('', $row);
$vid = $row['Vid'];
$banner = $row['banner'];
$cid = $row['category'];
$sid = $row['Scategory'];
if ($cid = 2 && $sid = 1){
echo
'
<div style="display:inline-block;">
<div style="border-color:blue; border-style:solid;">
<a href="#test'.$vid.'">
<img src="'.$banner.'" />
</div>
</div>';
echo $vid;
echo $cid;
echo $sid;
if ($vid % 2 == 0){
echo '<br>';
}
}
}
require'close.php';
?>
</body>
</html>
Now the code runs just fine, but it gets strange I use $cid and $sid as conditions in that IF loop. Given there is 20 records, both $cid and $sid have half their values as '1' and half as '2, so when I set the IF conditions I figured it would return 5 records, but it instead returned all 20. When I echo $vid $cid and $sid, it returns the proper $vid, but $sid returns as whatever condition I set it to. For example conditions set to $cid=1 and $sid=2 returns 1:1:2, 2:1:2, 3:1:2 etc.
Now here is where it gets really strange, regardless of the condition set for $cid it returns as '1', if I set it '7' it still returns as '1'. Whereas $sid returns as whatever number is set. Also when I set either condition to null it returns nothing.
So my question is why it's acting the way it is or how it should be written if I'm writing it wrong.
Also as a side question, when I put <a> before <img> it returns the proper ID that's linked to the <img>. But when I put <a> directly after <img>, it returns the ID of the next iteration's row, and the first iteration returns blank. Anyone happen to know why that happens since regardless of their position in the statement it's still part of the same loop iteration?
You are using a single equal and assign the value to the variable. To compare values you have to use == or ===!
What is the difference between == and ===?
See the following condition to see the difference:
2 == "2" -> Equal
2 == 2 -> Equal
2 === "2" -> Not Equal
2 === 2 -> Equal
How you can avoid this on future? - Yoda condition
You can change your conditions to the following to make sure you are using the conditions on the right way. You only shoud use this for equal comparison not for >, <, <=, >=.
//throws an error
if (0 = $isNull) { ... }
//the right one
if (0 == $isNull) { ... }
== not = in your if statement.
implode line does nothing
Use double-equals instead of singles. Not:
if( $foo = 2 )
...but:
if( $foo == 2 )
Your code is changing the values instead of testing them.
Change if ($cid = 2 && $sid = 1) with if ($cid == 2 && $sid == 1). I think you did it only by mistake, since your other if is fine!
In your if statement you're using a single equals operator it needs to be == or ===

Are two intergers equal PHP/CodeIgniter?

A very simple query that I cannot seem to figure out...
I'm using the CodeIgniter framework.
I'm retrieving data from my database and accessing the cols within the returned row via:
$item->available
where 'available' is the column of type int.
Now, I'd like to check whether the returned integer is 1 or not.
I believed this would be a simple case of
if ($item->available == 1) {
echo "Available";
} else {
echo "Sold";
}
}
However, this is not working. Can somebody please offer me some direction?
== will only equivelent, so true == 1 '1' == 1 etc.. to match type use === this will ensure only (int)1 === (int)1
And for consistancy, use type-casting to ensure type like so...
if ((int)$item->available === 1) {
echo "Available";
} else {
echo "Sold";
}

PHP - IF-statement false, still runs

The last hour I've been sitting with this problem. I have two if-statements (for testing purposes they are both IF-statements, and not IF- and ELSE IF-statements. The code runs the false IF-statement as if it is true.
The code:
<?php
$sth = $pdo->query("SELECT * FROM myDBTable WHERE alien1='$idkod' OR alien2='$idkod'");
$result = $sth->fetchAll();
if(!$result)
{
echo "No data";
}
else
{
foreach($result as $row)
{
$alien1 = $row['alien1'];
$alien2 = $row['alien2'];
if($idkod == $alien1)
{
echo $idkod . "==" . $alien1;
}
if($idkod == $alien2)
{
echo $idkod . "==" . $alien2;
}
}
}
?>
This will give me the following text on screen:
1234567891234567891234567==1234567891234567891234567
1234567891234567891234567==1234567891234567891234568
Clearly, the second text shouldn't be there, as the statement is not true.
Don't assume anything when making conditional forks, use var_dump() on the variables to temporarily look inside them - that way you best decide how to check for the exact type and value you are expecting.
Then as said already, prefer to check using ===
If you adopt this behaviour you will save countless hours and avoid some quite subtle bugs which can appear in your code.
Having the PHP Truth Tables pinned up for a while will help.
== ignores type when testing for equality. In this case it will assume that both strings are numbers and convert them. This means this will turn into:
9223372036854775807 == 9223372036854775807 //Max int val. Will be different on different systems.
=== will make sure that both arguments are the same type and will not attempt to coerce making
'1234567891234567891234567' === '1234567891234567891234568';
Give the expected result.
PHP equality is wacky sometimes.
It is wrong to use == you need to use === the second is value comparison, the first is object comparison (depending on the context)
I have modified your code a little check it
<?php
$sth = $pdo->query("SELECT * FROM myDBTable WHERE alien1='$idkod' OR alien2='$idkod'");
$result = $sth->fetchAll();
if(!$result)
{
echo "No data";
}
else
{
foreach($result as $row)
{
$alien1 = $row['alien1'];
$alien2 = $row['alien2'];
if($idkod == $alien1 && $idkod != $alien2)
{
echo $idkod . "==" . $alien1;
}
if($idkod == $alien2 && $idkod != $alien1)
{
echo $idkod . "==" . $alien2;
}
}
}
?>

as of now it just ignores the if statement and gives them a ticket everytime.php, mysql, If else

Alright so i'm trying to put value in an array and shuffle them to be random, then have it use that random value in a query. I know my code is bad and not to use mysql anymore lets stay off that topic please.
I don't understand why this isn't working I have other things like it that work just fine.
right now it ignores the if statement and gives them a ticket each time.
if(isset($_POST['Submit'])) {
$ticket = array("0","0","0","0","0","0","0","1");
shuffle($ticket);
if ($ticket >= 1) {
echo "You have Found a Shop Ticket!" ;
mysql_query("UPDATE users SET ticket=ticket+1 WHERE username = '".$_SESSION['username']."'")
or die(mysql_error());
} else {
echo "";
}
}
You're checking if the entire array is >= 1, which is obviously TRUE all the time.
Pick a value instead:
$ticket = array_shift($ticket); // do this after you shuffle
try
if (current(shuffle($ticket)) >= 1) {
# yay
} else {
# ney
}
$ticket is an array, not a number.
u could use foreach or array_map to do this.
example:
function foo($n){
if($n >= 1){//do something}
}
$ticket = array("0","0","0","0","0","0","0","1");
shuffle($ticket);
array_map('foo', $ticket);

mysql_fetch_row returns value above zero despite actually being zero

I'm running the following query but $new returns 0:
$count = mysql_query("SELECT COUNT(*) FROM flagged WHERE status=0") or die(mysql_error());
$new = mysql_fetch_row($count);
if ($new != 0) {
echo "<script language=\"javascript\">$.titleAlert(\"New Logs - ($new[0])\");</script>";
}
Problem is the if-condition keeps getting met when it shouldn't when $new != 0
I even tried:
if ($new > 0) {
//update title about new logs
}
Either way, the title is still updated and I'm not sure why.
New Logs - (0)
just do
var_dump($new);
and you'll see why your if doesn't work
Not sure what you mean. $new should be an array not a scalar value per the PHP documentation.
mysql_fetch_row documentation
this code
$new = mysql_fetch_row($count);
makes $new becomes an array
try to compare it like this:
if ($new[0] != 0)
or even better, so You would be 100% sure it's what You need.
if (count($new) == 1 && intval($new[0]) != 0)
mysql_fetch_row should return an array or FALSE.
Maybe adjust your conditional to:
if ( !$new ) {
// some code here
}

Categories