Loop not working as expected

Sorry to have to ask for help. I’ve been working on this issue for a few days and I just can’t seem to find the error or my ways. (Could have something to do with the percocets the Oral Surgeon gave me. [Grin]) I’m trying to get a loop to read each line, check for the value and if the value is ‘X’ I want it to write a Y instead. However even after all the tweaking I’ve done it writes the Y to every field. I can’t see where I’m going wrong. And yes, I’ve been doing the testing on a copy of the real data.

//  sets connect to server string

$conn = mysqli_connect('localhost', 'XXXXXXX', '*********', 'billboard');
// check connection

if (mysqli_connect_errno($conn))   {
    echo "Failed to connect to MySQL: " . mysqli_connect_error();
$result=mysqli_query($conn, "SELECT * from data4 order by id");
$num_rows = mysqli_num_rows($result);    
while($record = mysqli_fetch_array($result)) {
    if(!empty($record)) {        
        // echo $record['id'] . "  " . $record['onchart'] . "  " . $record['have'] . "  " . $record['raporhm'];
        if ($onch='X')  {
        } else {
        $UpdateQuery = "UPDATE data4 SET onchart = '$onch' where id = '$id' ";    
        mysqli_query($conn, $UpdateQuery);

echo "Done";

Hi Jim,

Your problem is with your IF condition:

if ($onch='X')  {

by using a single equals sign you’re assigning the value ‘X’ to $onch. The IF statement always evaluates to TRUE, and $onch then gets assigned the value ‘Y’, for every record.

To do equality checks you need to use double equals (==) or triple equals (===). The difference is that with the first PHP will do type conversion (so 4 == ‘4’ would be true) whereas the second doesn’t (so 4 === ‘4’ would be false, but 4 === 4 would be true).

Also, note that you don’t need to do

if(!empty($record)) {

as the while statement only loops as long as there are results, so checking for empty rows is redundant.

@fretburner thank you so much. That was the whole problem. I remember reading about that when I first started to learn PHP but I forgot about it. I also deleted the other line. I borrowed the code from another page where I needed that check. Thanks again.

PHP shares this trait with Java, JavaScript and C, and it can be useful if the assignment is negative. It so easily confuses people though that a few programming languages, such as Python, forbid assignment during conditional evaluation simple because the confusion it causes isn’t worth the benefit. There are also companies that forbid using = in an if statement as part of their code writing policies.

Thanks @Michael_Morris. That’s good to know. Now I only hope I can remember it! [Grin]

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.