Click here to Skip to main content
15,885,365 members
Please Sign up or sign in to vote.
5.00/5 (1 vote)
See more:
As the title says I'm looping with if statement to find a key-value from an array called $decoded so basically the function is like this if the $product-$key equals $item and $product->$key2 equals $ProductId then edit the specific key-value at first I tested the code in this way and it works

PHP
$decoded = json_decode( $fetched );
                
$stmt=$this->connection->prepare('update `bills` set `items`=:json where id=:id');


foreach( $decoded as $index => $product ){
    
    if( $product->$key == $item ){ // just the $Product->$key and it works fine
        $decoded[ $index ]->$key = $value;
        $json = json_encode( $decoded );
        
        $stmt->execute([
            ':json' =>  $json,
            ':id'   =>  $bid
        ]);
    }                   
}


but when I added this $product->$key2 == $ProductId it stopped working so what I'm missing here?

What I have tried:

Full Code:-

PHP
public function AlterJSON( $bid=false, $item=false,$ProductId=false, $key=false, $key2=false, $value=false ){
    try{
        if( $bid && $item && $key && $value && $ProductId && $this->connected === true ){
            
            $stmt=$this->connection->prepare('select `items` from `bills` where `id`=:id');
            $stmt->execute( [ ':id' => $bid ] );
            
            $fetched = $stmt->fetchColumn();
            $decoded = json_decode( $fetched );
            
            $stmt=$this->connection->prepare('update `bills` set `items`=:json where id=:id');
            
            
            foreach( $decoded as $index => $product ){
                
                if( $product->$key == $item && $product->$key2 == $ProductId ){
                    $decoded[ $index ]->$key = $value;
                    $json = json_encode( $decoded );
                    
                    $stmt->execute([
                        ':json' =>  $json,
                        ':id'   =>  $bid
                    ]);
                }                   
            }
            return true;
        }
        return false;
    } catch( PDOException $e ){
        return $this->errors === true ? $this->error( $e->getMessage() ) : false;
    }
}


Function Call
PHP
$call =  $dbConnection->AlterJSON( $BillID, $CurrentPrice,$id, 'price','id', $ProductPrice );
print_r(var_dump($call));
Posted
Updated 30-Jul-20 18:09pm
v2
Comments
Richard MacCutchan 31-Jul-20 3:52am    
Use the debugger to check the values you are comparing.
[no name] 31-Jul-20 13:01pm    
PHP started out as someone's hobby.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900