0

I have an array of items that I am looping over and checking if the value already exists in the database, if it does I would like to update it, if it does not I would like to create a new entry. The first item in the array is seen and returns true, but anything after the first one returns 0 even if I know for a fact that it is in the database with the correct item_name and ticket_id.

I have tried researching before asking, but am stumped at this point. Thanks for any help in advance.

if($func == 'edit') {

        foreach ($addItem as $key => $value) {
            if (empty($key) || $key=='amount_paid') {
    continue;
  }
            $ticket_items = mysql_query("SELECT * FROM ticket_items WHERE ticket_id = '$ticket_id' AND item_name = '$key'");
            if (mysql_num_rows($ticket_items)) {
                print 'Updated '. $key ."\n";
                mysql_query("UPDATE ticket_items set item_name='$key', item_price='$value' WHERE ticket_id='$ticket_id'");
            } else {
                print 'Created '. $key ."\n";
            mysql_query("INSERT into ticket_items (ticket_id, item_name, item_price) VALUES ('$ticket_id', '$key', '$value')");     
            }
        }
}
3
  • The $ticket_id is the same in every iteration of your loop. Is that intended? Commented Oct 4, 2014 at 17:23
  • yes all items in the array have the same ticket_id Commented Oct 4, 2014 at 17:26
  • maybe it is skipping you should add echo in (empty($key) || $key=='amount_paid') condition also count the array Commented Oct 4, 2014 at 17:29

2 Answers 2

1

Notice that, in your UPDATE statement, you are updating every row that has the same $ticket_id, regardless of the item_name. It should be:

UPDATE ticket_items set item_name='$key', item_price='$value' WHERE ticket_id='$ticket_id' AND item_name='$key';
Sign up to request clarification or add additional context in comments.

1 Comment

So simple, I can't believe I missed that. Thank you!
1

It looks like at the first update, you are resetting the data for all Tickets in the db.

mysql_query("UPDATE ticket_items set item_name='$key', item_price='$value' WHERE ticket_id='$ticket_id'");

Above one sets the key and value to the same value for all the rows of that ticket.

you should try smt like below:

mysql_query("UPDATE ticket_items set item_price='$value' WHERE ticket_id='$ticket_id' and item_name='$key'") ;

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.