0

using PDO, I receive 1+ rows and turn them into an array like this:

while($row = $car_sales->fetch(PDO::FETCH_ASSOC)){          
    $car_id_array[] = $row["car_id"];
    $car_type_array[] = $row["car_type"];
    $dealer_id_array[] = $row["dealer_id"];
    $buyer_id_array[] = $row["seller_id"];
}

I'm trying to simply "mix" each level of the array to act as a unit and go down the foreach loop together, submitting the $q query in order. In other words, something like this:

foreach($dealer_id_array as $dealer_id) {
    if ($car_type=='new') {
        if ($dealer_id==$buyer_id){
          $q = 'UPDATE car_sales SET new_cars=new_cars+1 WHERE dealer_id=:dealer_id';
        } else if ($dealer_id!=$buyer_id){
          $q = 'UPDATE car_sales SET new_cars=new_cars-1 WHERE dealer_id=:dealer_id';
    } else if ($car_type=='old') {
        if ($dealer_id==$buyer_id){
          $q = 'UPDATE car_sales SET old_cars=old_cars+1 WHERE dealer_id=:dealer_id';
        } else if ($dealer_id!=$buyer_id){
          $q = 'UPDATE car_sales SET old_cars=old_cars-1 WHERE dealer_id=:dealer_id';
    }
    $car_update = $dbhandle->prepare($q);
    $car_update->execute(array(':dealer_id' => $dealer_id));
}

The loop should run with the first array values if there is only one value retrieved from the while loop. If there are more, the foreach should run as many times as there are dealer_ids from the while loop, while respecting the order. This example won't work, but I'm looking for possible solutions to solve this issue correctly. What do you think would be the most efficient way to do this?

1 Answer 1

2

I might be misunderstanding you, but I believe if you just replaced your foreach loop with a for loop, and counted one of the arrays you would solve your issue:

 for($i = 0; $i < count($dealer_id_array); $i++) {

and then simply using $i to access the correct item in your arrays:

$car_type_array[$i];

But having said that, I don't really see the point of the initial four arrays in the first place. Could you not just directly execute the code inside the foreach loop straight inside the while loop in the first place?

EDITED: to fix code example

Sign up to request clarification or add additional context in comments.

2 Comments

Works great, thank you pburgess. The code should say "for" instead of "foreach" for the loop to work though:) I tried editing it but it needs more changes than that to allow the edit, maybe you can edit it? Thanks again!
Sorry, typo, I fixed the example now.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.