Pergunta

I am using a mysql convention similar to this for inputing form information

form_id - INT PRI
user_id - INT
field_name - VARCHAR
field_value - TEXT

I have a PHP script currently that goes through a foreach loop of all the form fields and first checks if it exists, if the count is greater than 0, then it updates the field. If it doesn't exist, then it inserts the row. Unfortunately, I am trying to process over a hundred fields through the PHP script, and this method proves to be very time consuming. What is a faster way of doing this? I don't think I can use on duplicate key update because only form_id is unique.

How each row would be like this:

1, 1, name, Andy
2, 1, date, 2012-10-05
3, 2, name, John

Does that kind of make sense?

Nenhuma solução correta

Outras dicas

I see this is MySQL. And after your description you're doing a double job with PHP. Just collect all values and fire them with the correct SQL into the database. For that you can use MERGE STATEMENTS, which is available on nearly all DB Systems, just in a different syntax. A merge statement is inserting a row, and if a row already exists it just updates the row with the new values. Or you can say it should ignore the row etc. Many possibilities.

For example (NOT MYSQL!):

 MERGE INTO tablename USING table_reference ON (condition)
   WHEN MATCHED THEN
   UPDATE SET column1 = value1 [, column2 = value2 ...]
   WHEN NOT MATCHED THEN
   INSERT (column1 [, column2 ...]) VALUES (value1 [, value2 ...

In MySQL it is a little bit different. There you use the INSERT... ON DUPLICATE UPDATE

http://dev.mysql.com/doc/refman/5.1/en/insert-on-duplicate.html

For this here is an example (did not use your fields):

INSERT INTO table (table.a, table.b, table.c, table.d)  -- define your insert statement
VALUES  -- use the VALUES command to add several rows, or just one. Depends on your interface
('key1','key2','exampleVal','exampleValb'), 
('key1','key3','exampleVal2131','exampleValasfasf')
ON DUPLICATE KEY UPDATE  -- Here the check appears. If the Values with key (a) + key (b) exist it will just UPDATE the fields c and d with VALUES(table.c) and VALUES(table.d)
table.c = VALUES(table.c),
table.d = VALUES(table.d)

I Hope I made this anyhow understandable. But this can save you LOTS of time!

Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top