0

im currently trying to update an array with values from another one. Basically there is a form where you can update data for an object, the form sends a json array like so:

{
    "name": "Test2",
    "address": "Adresas 2",
    "object_id": "44",
    "job_id": [
            "31",
             "33"
             ],
    "amount": [
        "500",
        "500"
    ]
}

My goal is to update another array that is being fetched from the database with values of job_idd and amount.

The array from database looks like so:

{
    "jobs": [
        {
            "id": "31",
            "amount": "500",
            "have": 250
        },
        {
          "id": "33",
          "amount": "500",
          "have": 0
        }
    ]
}

I need to update the second array values "amount" with the posted values from the first array "amount", but so that the second array still has the original "have" values

I tried using nested foreach method:

$object_id = $_POST['object_id'];
$data = json_encode($_POST);
$json = json_decode($data, true);
$i = 0;

foreach($json['job_id'] as $item) {

    $job_id = $item;

    $query33 = "SELECT * FROM `objektai` WHERE id='$object_id'"; 
    $result33 = mysqli_query($conn, $query33) or die(mysqli_error($conn));
         
    while($row2 = mysqli_fetch_array($result33)){
        $job_info = $row2['info'];
    }

    $json_22 = json_decode($job_info, true);

    foreach ($json_22['jobs'] as $key2 => $entry2) {
        $have = $json_22['jobs'][$key2]['have'];
    }

    $result["jobs"][] = array(
        'id' => $job_id,
        'kiekis' => $json['amount'][$i],
        'turima' => $have,
        );

    $i++;
}

Usinng the example above the foreach prints the values 2 times and my updated json "have" has a value of 0, the "amount" entries are updated correctly

Thanks in advance for you help!

UPDATE

adding var_export($_POST):

array ( 'name' => 'Test2', 
        'address' => 'Adresas 2', 
        'object_id' => '44', 
        'job_idd' => array ( 
                0 => '31', 
                1 => '33', 
        ), 
        'darbo_kiekis' => array ( 
                0 => '500', 
                1 => '500', 
        ), 
    )
RiggsFolly
  • 93,638
  • 21
  • 103
  • 149
  • Good code indentation would help us read the code and more importantly it will help **you debug your code** [Take a quick look at a coding standard](https://www.php-fig.org/psr/psr-12/) for your own benefit. You may be asked to amend this code in a few weeks/months and you will thank me in the end. – RiggsFolly Jan 03 '22 at 15:49
  • 1
    **Warning:** You are wide open to [SQL Injections](https://php.net/manual/en/security.database.sql-injection.php) and should use parameterized **prepared statements** instead of manually building your queries. They are provided by [PDO](https://php.net/manual/pdo.prepared-statements.php) or by [MySQLi](https://php.net/manual/mysqli.quickstart.prepared-statements.php). Never trust any kind of input! Even when your queries are executed only by trusted users, [you are still in risk of corrupting your data](http://bobby-tables.com/). [Escaping is not enough!](https://stackoverflow.com/q/5741187) – Dharman Jan 03 '22 at 15:50
  • 1
    It is a very bad idea to use `die(mysqli_error($conn));` in your code, because it could potentially leak sensitive information. See this post for more explanation: [mysqli or die, does it have to die?](https://stackoverflow.com/a/15320411/1839439) – Dharman Jan 03 '22 at 15:50
  • Start by showing us a `var_export($_POST);` please – RiggsFolly Jan 03 '22 at 15:52
  • 1
    What's the point of converting `$_POST` to and from JSON? – Barmar Jan 03 '22 at 16:32
  • Why do you use two variables `$item` and `$job_id`? Why not just `foreach ($_POST['job_id'] as $job_id)`? – Barmar Jan 03 '22 at 16:33

1 Answers1

0

When you're looping through the array from the database, you need to compare the id value with $obj_id.

I've also shown below how to use a prepared statement to prevent SQL injection.

I've removed lots of unnecessary code:

  1. No need to convert $_POST to/from JSON.
  2. Use $i => in the foreach loop to get the array index.
  3. You don't need a while loop when processing the query results if it only returns one row.
  4. You don't need $key2, you can just use $entry2.
$object_id = $_POST['object_id'];

$query33 = "SELECT * FROM `objektai` WHERE id = ?"; 
$stmt33 = $conn->prepare($query33);
$stmt33->bind_param('i', $job_id);

foreach($_POST['job_id'] as $i => $job_id) {
    $stmt33->execute();
    $result33 = $stmt33->get_result();
    $row2 = $result33->fetch_assoc();
    $job_info = $row2['info'];

    $json_22 = json_decode($job_info, true);

    foreach ($json_22['jobs'] as $entry2) {
        if ($entry2['id'] == $job_id) {
            $result["jobs"][] = array(
                'id' => $job_id,
                'kiekis' => $json['amount'][$i],
                'turima' => $entry2['have']
            );
        }
    }
}
Barmar
  • 741,623
  • 53
  • 500
  • 612