CaitlinHavener
CaitlinHavener

Reputation: 1418

Query error update field mysql

I am very frustrated with the function below. It is not updated my flag in the database. I have tried putting the ones and zeros inbetween quotes and not. I have the field set to small integer in database. Do you see what I am doing wrong? The entry is there but the 1 is not updating to 0.

function postValue(){
    global $customerID;
    $query="SELECT flag FROM welcomecall WHERE customerID= '$customerID'";
    echo $query;
   $result = mysql_query($query) or die('Error in the query: ' . mysql_error());
   while ($row = mysql_fetch_assoc($result)) {
    echo "The customer flag is ". $row["flag"];  
    }

    if ($row['flag']=='0'){
    $query="UPDATE welcomecall SET flag='1' WHERE customerID='$customerID'";            
   $result = mysql_query($query) or die('Error in the query: ' . mysql_error());
   }
   else if($row['flag']=='1'){
    $query="UPDATE welcomecall SET flag='0' WHERE customerID='$customerID'";            
   $result = mysql_query($query) or die('Error in the query: ' . mysql_error());
   }
}

Upvotes: 0

Views: 93

Answers (2)

John Conde
John Conde

Reputation: 219804

Looks like you're using logic outside of your loop that belongs inside of your loop:

function postValue(){
    global $customerID;

    $query="SELECT flag FROM welcomecall WHERE customerID= '$customerID'";
    echo $query;

    $result = mysql_query($query) or die('Error in the query: ' . mysql_error());
    while ($row = mysql_fetch_assoc($result)) {
        echo "The customer flag is ". $row["flag"];  

        // Moved
        if ($row['flag']=='0'){
            $query="UPDATE welcomecall SET flag='1' WHERE customerID='$customerID'";            
            $result = mysql_query($query) or die('Error in the query: ' . mysql_error());
        }
        else if($row['flag']=='1'){
            $query="UPDATE welcomecall SET flag='0' WHERE customerID='$customerID'";            
            $result = mysql_query($query) or die('Error in the query: ' . mysql_error());
        }
    }
}

Upvotes: 0

Andomar
Andomar

Reputation: 238068

When the while expression exits, there'll be no $row left:

while ($row = mysql_fetch_assoc($result)) {

So this will not be true:

if ($row['flag']=='0'){

Consider moving the if statements inside the while loop.

Upvotes: 2

Related Questions