Latest From The Blog

Service announcements and product updates from the Mad Capsule team

James

Saving Form Data Twice in CakePHP

February 28th, 2009 by James in php

CakePHP makes it increbibly easy to insert data into MySQL tables with the use of their inbuilt form helper and and save function however one question I have seen alot is how to save form data more than once equating to multiple row inserts? The answer is actually quite simple. When you use the CakePHP save method, CakePHP holds on to the last primary ID it created, and so if you try using the save method again, in the same session.. nothing happens, as the row already exists as far as Cake is concerned. You need to make Cake forget about the last primary ID it's holding.

$this->Whatever->create(); $this->Whatever->save($this->data); $this->Whatever->create(); $this->Whatever->save($this->data);

The code above runs the create() method on the Whatever model reseting any primary ID Cake was holding for it. Then it runs the save method saving the form data to the Whatever model. It then runs the create method again, resetting the primary ID and then saves the form data again, giving you two rows in your table with the same data all bar the primary key.

Of course you would more than likely put your save in a loop of some kind if you were planning on multiple saves.

$inserts_required = 1;

while ($inserts_required <= 10) { $this->Whatever->create();

$this->Whatever->save($this->data));

echo $inserts_required++; }

The above will insert 10 rows with the same data, bar the primary ID.

comments powered by Disqus

OUR AUTHORS

Mark
Mark

I like the Sea, Monkeys, the Internet and sun. I don't like olives

James
James

Less QQ more pew pew

Israel
Israel

I love time travel, infact I'm writing this from the 1920s

CATEGORIES