I'm trying to get the ID from an INSERT query with CAKEPHP.
In this case I'm not working with the Model itself so I'm not using the following code:
$this->ModelName->save($data);
//Then...
$this->ModelName->getInsertID();
$this->ModelName->getLastInsertID();
I'm just using
$this->query("INSERT.......");
How can I get the Inserted ID with CakePHP without referencing the model?
I think that the problem is that the query is beeing cached.
If you see the logs the query isn't even been executed (I tried your code)
try this instead
$this->query("SELECT LAST_INSERT_ID();" , false);
see manual
http://book.cakephp.org/2.0/en/models/retrieving-your-data.html#model-query
$this->query('SELECT LAST_INSERT_ID()');
See LAST_INSERT_ID() in the MySQL documentation.
Related
I am trying to write some custom insert/update queries with custom logic like
$rs = $writeConn->query($myQuery);
And it works ok, but after this, how do I check if the query executed successfully or if there was an error? also how do I get the lastInsertId?
Hello Mage::log() is used for get query error.
Get last inserted id check code may be help you
$writeConn ->lastInsertId();
I am doing some PostGIS work on a CakePHP application.
Because I've been working with some database functions, I've done raw $this->query() calls to do inserts of data. I'm at a point where I need to get the ID of the result of an insert query, but $this->query() returns an empty array.
Here is the query I'm using for inserts:
INSERT INTO locations (title,company_id,state_id,poly,point)
VALUES ('$title',$company_id,$state_id,ST_GeomFromText('$geom',4269),$point);
The problem is Cake is trying to insert 'ST_GeomFromText('$geom',4269)' as a string, and I cannot figure out how to get it to remove the quotes in the SQL insert statement it prepares via $this->Location->save();.
Any suggestions?
Edit:
Before I was doing $this->query(); and my SQL works fine. That's not the issue.
Now when I do:
$this->Location->create();
$this->Location->set('poly',$poly);
... Set all the rest of the model fields ...
$this->Location->save();
The SQL that gets produced looks like this:
INSERT INTO locations (title,company_id,state_id,poly,point)
VALUES ('Some Title',5,23,'ST_GeomFromText('$geom',4269)',POINT(-72.342,102.23455);
Because ST_GeomFromText gets 'quoted', PostgreSQL throws an error and doesn't insert the geometry.
The solution to my problem turned out to NOT be a CakePHP based one, but a PostgreSQL one!
By appending "RETURNING id" to the query like this:
INSERT INTO locations (title,company_id,state_id,poly,point)
VALUES ('$title',$company_id,$state_id,ST_GeomFromText('$geom',4269),$point) RETURNING id;
The query no longer returns an empty array, and now returns the ID of the row it just created!
Via $this->ModelName->getLastInsertID(); you are able to get the last inserted ID. So, after a save you can call this code to get its id.
I am trying to implement pagination in my search results with Yii. I have pagination working on my browse record pages, but for some reason, am having trouble with getting it working in search.
So far, I have the following SQL to produce the search results:
SELECT SQL_CALC_FOUND_ROWS DISTINCT user.id FROM user, personal_info WHERE (personal_info.bio LIKE '%a%' ) AND personal_info.user_id = user.id AND user.role = 'F' LIMIT 0, 8;
Which is passed to ActiveRecord as follows:
$results = $this->findAllBySql($sql);
Immediately afterwards I run this code:
$rows = $this->findBySql("SELECT FOUND_ROWS() as row_count;");
echo $rows->row_count;
Strangely, I am receiving the following error when I try and execute the above code:
Property "Search.row_count" is not defined.
For some reason, Yii is not able to retrieve the FOUND_ROWS value from MySQL.
I have pretty much exactly the same PHP code in my browse records page (but different SQL), and it works perfectly. Not sure why in this situation Yii is unable to retrieve the FOUND_ROWS value. I've tried running this code directly inside MySQL to see if there was something wrong with my SQL, but it retrieves the FOUND_ROWS value with no problems - this problem only happens when I try to do it inside Yii.
Any idea what I maybe doing wrong?
Many thanks!
Turns out that I needed to define $row_count inside the model before it would recognise it as a variable I can refer to.
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?
I think you just want to do:
$this->getLastInsertID();
http://book.cakephp.org/2.0/en/models/additional-methods-and-properties.html#model-getlastinsertid
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(...)).
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.
You can get last inserted record id by
echo $this->ModelName->getLastInsertID();
Alternately, you can use:
echo $this->ModelName->getInsertID();
This methods can be found in cake/libs/model/model.php on line 2775
Note: This function doesn't work if you run the insert query manually
I have a MySQL query that goes as follows (using Zend_Db):
$sql = $handle->quoteInto("UPDATE board SET rank=rank+1 WHERE post_id=?", $postid);
$handle->query($sql);
(Rank isn't an auto-incrementing PK).
I would like to now retrieve the value of rank without preforming another query.
I've tried $handle->lastInsertId(); but it doesn't seem to work , since I didn't use MySQL's natural auto-incrementing method (I can't - rank is the rank of a post. I either ++ or -- it.)
Any way to do this with preforming another query? A function that will return the last changed value?
I don't believe this is possible - you'll just have to do a SELECT.
You can use the LAST_INSERT_ID function that MySQL provides to set a value and then make it available via the mysql_insert_id() C function that the $handle->lastInsertId(); relies on.
The following is an updated version of your code snippet with the LAST_INSERT_ID changes made to it:
$sql = $handle->quoteInto("UPDATE board SET rank=LAST_INSERT_ID(rank+1) WHERE post_id=?", $postid);
$handle->query($sql);
Let me know if you have any questions.
HTH,
-Dipin