views:

197

answers:

1

I am currently structuring my queries for a database update model with CodeIgniter.

I getting the form posted input keys with $keys = array_keys($_POST)

To update according database fields I was wanting to do something like this

foreach($keys as $key){
    $data = $this->input->post($key);
    $this->db->query("Update $table SET '$key'='$data' WHERE user_id='$the_user->id'");  }

(this is not production code, just trying to illustrate my question, hence no escaping, validation, etc...)

My question is, does this pose a performace problem by running a seperate query for each individual piece of form data submitted?

EDIT: sorry didn't intend for it to sound like a yes or no question, obviously if yes or no, the answer is yes, but I am looking for more of to what degree does it hamper the performance?

+1  A: 

Yes.

You're issuing multiple updates, rather than one. The performance impact is less likely to be in your php loop, and more in the database connection; thus minimizing the amount of transactions between your application and the database will improve performances.

You can try:

  1. build your SQL string before submitting:

    UPDATE <table> SET key1=data1, key2=data2, key3=data3 WHERE user_id=<user>
    
  2. executing multiple updates in the same transaction:

    $this->db->query("
        UPDATE <table> SET key1=data1 WHERE user_id=<user>;
        UPDATE <table> SET key2=data2 WHERE user_id=<user>;
        UPDATE <table> SET key3=data3 WHERE user_id=<user>;"
    );
    

I'm not sure how PHP/MySQL handle the second option. Perl/Postgres can do it. Also, I would think that the first option would be faster.

Another thing to consider, if you're doing this for multiple users, is to use an IN (eg WHERE user_id IN ($user_list), where $user_list is a string of users in the format 'user1','user2','user3').

vol7ron
updated question to reflect my hopes for the answer, sorry I wasn't clear before.
jon
The performance impact would depend on how many key/value pairs you have, how many queries are being executed, how large the tables are, etc. If you're only executing 5 queries, this should be almost instantaneous. The bigger performance impact would be to make sure the `user_id` field is indexed.
vol7ron
As you stated, that is not production code, so if your query is more advanced (multi-joins), then you'd really want to reduce the number of queries submitted (option 1).
vol7ron
Thanks, the only reason I'm not doing option one is because I'm dealing with a variable number of keys.
jon
and since I'm really only dealing with say 4-8 values, I probably will not worry about it at this point.
jon
But it'd be just as easy to do: `foreach($keys as $key){ $key_value .= ",'$key'='" . $this->input->post($key) . "'";} $key_value = substr($key_value,1); $this->db->query("UPDATE <tbl> SET $key_value ...");` --- again, as you stated, this is an example and not production code - it's hazardous and open to SQL injections.
vol7ron