views:

73

answers:

2

Hello I am using cakePHP 1.3 and I am unable to retreive the last inserted row's id. I actually am using $this->Model->id to retreive the last inserted id but I am unable to get the id. When tried to check what is return type, it says as bool(false), which means nothing is returned.

Here I am loading a different model in a different controller, so would that be the issue?? But even though I am loading, I get back nothing!!

$this->loadModel('Contact');
$this->Contact->query("insert into contacts(tblContact_firstName,tblContact_lastName,tblContact_company,tblContact_department,tblContact_address,tblContact_country,tblContact_city,tblContact_state,tblContact_zipcode,tblContact_phone1,tblContact_email1) values('$sanitizedFormData[fname]','$sanitizedFormData[lname]','','$sanitizedFormData[company]','$sanitizedFormData[address]','$sanitizedFormData[country]','$sanitizedFormData[city]','$sanitizedFormData[state]','$sanitizedFormData[zip]','$sanitizedFormData[phone]','$sanitizedFormData[email]');");

$this->loadModel('Contact');
$contactId = $this->Contact->id;

And when I printed the $this->Contact array recursively, I found the value of "id" key empty. So that explains why I was receiving an empty value.

Now given my situation, how would I get the last inserted id, specific to the controller Contact?? Is it possible?

+2  A: 

If this is MySQl you could use "SELECT from contacts LAST_INSERT_ID()" query to get last ID. or just "SELECT LAST_INSERT_ID()"

For MSSQL it is "SELECT @@IDENTITY".

This bypasses any solution in cakePHP though, so there might be a better solution.

David Mårtensson
Thank you for the comment!
macha
+3  A: 

When you use query() you loose a lot of automagic cakephp provides. Use save() instead.

In fact, you even do not need to load Contact in this case. You can execute any query from the current controller with query() even saving to any other table.

You can also avoid using loadModel() if your current model is somehow associated with Contact ($this->CurrentModel->AnotherOne->Contact->save(...)).

bancer
So if I use save, then would I be able to retrieve the last insert id?
macha
I hope yes. At least I have never had the problem with retrieving last insert id. Take a look here too - http://api13.cakephp.org/class/model#method-ModelgetLastInsertID.
bancer
@macha yes, it's the save() method usage that will automatically set the model's ID. In general, try to use the Cake built-ins; they do a lot of handy stuff automatically for you (like setting the model id).
Travis Leleu
@bancer Also, how would I know how a current model is connected to another one and that other model is connected to my destination model
macha
If you have correct associations defined in the models they will be connected by calling them the way I mentioned above.
bancer