I want to edit a JSON object, so made method called alterJSON the function find the specific JSON array from the database and then change the key-values based on the parameters was given
so my question is as you can see in this foreach loop there is an (if statement)
foreach( $decoded as $index => $product ){
print_r('<pre>');
if( $product->$key == $item) {
echo ('found');
$decoded[ $index ]->$key = $value;
$json = json_encode( $decoded );
$stmt->execute([
':json' => $json,
':id' => $bid
]);
}
}
the loop will print found and make some changes on the $JSON by MySQL query and that's perfectly working, but it will only find the JSON object or item even if there are more then one item in the same key-value so, I want to make another condition in the statement that checks a unique key-value
called id so how can I accomplish that? I made some attempts and failed.
what I have tried
<?php
public function AlterJSON( $bid=false, $item=false, $key=false, $Product, $id, $value=false ){
try{
if( $bid && $item && $key && $value && $Product && $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 ){
print_r('<pre>');
if( $product->$key == $item && $product->$id == $Product) {
echo ('found');
$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:-
$call = $dbConnection->AlterJSON( $BillID, $CurrentPrice,'price', $ProductID,'id', $ProductPrice );
$product->id == $idinstead? and wouldn't you think it would be easier to delegate this in another table making the id just a foreign key, instead of saving the whole json string, decoding and encoding and whatnotif( $product->$key == $item)?