Getting null when using getLastInsertID in cakephp2.10 - php

Getting empty value when calling getLastInsertID() in cakephp2.10
Mycode is
$this->query("INSERT INTO $savedtbl(ref_name,productdetails_id,users_id,type,image,saved_date,template_name) VALUES('$ref_name',{$paramsArray['Customimage']['productdetail_id']},'$uid','{$paramsArray['Customimage']['front_rear']}','$editedImg','$date','$template_name')");
$lastid = $this->getLastInsertID();
How to fix this? please help

As far as I know, Model::getLastInsertID() in Cake 2.x will return last inserted id only if that insert was made via Model methods, not plain SQL query. You should try this approach:
$this->Model->create();
$this->Model->set(...); //set your fields as needed
$this->Model->save();
$lastId = $this->Model->getLastInsertID();

Related

empty value after mysql update php

i made a lot of research around here and Google but i cannot find an answer to this problem.
I update a field in a MySQL database with following code:
public function registerPubKey() {
$stmt = $this->cn->prepare('UPDATE sb_user SET pubkey= ? WHERE email= ?');
$exres = $stmt->execute(array($this->info["pubkey"], $this->info["email"]));
if ($exres == false) {
$resultArray["result"] = "Error registering public key";
echo json_encode($resultArray);
exit;
}
$resultArray["result"] = "success";
echo json_encode($resultArray);
}
I'm sure that all works except that the field in the database is empty. I dumped the private variable $info and it contains the pubkey (pubkey is a base64 string).
I noticed that if I change the update query with an INSERT, the value is inserted correctly!
It's likely because you're trying to UPDATE non existent rows. Try adding a ON DUPLICATE KEY before. See INSERT ... ON DUPLICATE KEY UPDATE Syntax. UPDATE returns nothing if the row does not exist.
I ran into a similar issue and validated that:
the row existed, and
the execute parameters were valid and correct
The PDO::errorInfo() function can provide insight into what's actually happening to cause the update to fail:
if (! $stmt->execute($params) ) {
$resultArray["result"] = print_r($stmt->errorInfo(), true);
}
In my case, I got the message The user specified as a definer ('user'#'172.20.%.%') does not exist. Since this was a database snapshot restored to a different subnet, the error message makes sense and the user in-fact did not exist.

MySQL: Can't get LAST_INSERT_ID()

I'm creating an application using FuelPHP framework and MySQL and I'm trying to AJAX-update/insert a new log for an item already in DB.
This is my MySQL code:
UPDATE `work_orders` SET `status_id`='{$status}' WHERE `id` = '{$wo_id}';
INSERT INTO `work_order_logs`(`id`, `work_order_id`, `log_text`, `status_id`) VALUES ('{$id}', '{$wo_id}', '{$text}', '{$status}')
ON DUPLICATE KEY UPDATE `log_text`='{$text}',`status_id`='{$status}';
SELECT LAST_INSERT_ID() as id;
When this code is executed from phpmyadmin it runs successfully and returns the id, however when executed from FuelPHP it only returns 1, which I assume means a successful operation.
The FuelPHP code:
public static function updateLogById($id, $wo_id, $text, $status)
{
try {
$log_query = \DB::query("
UPDATE `work_orders` SET `status_id`='{$status}' WHERE `id` = '{$wo_id}';
INSERT INTO `work_order_logs`(`id`, `work_order_id`, `log_text`, `status_id`) VALUES ('{$id}', '{$wo_id}', '{$text}', '{$status}')
ON DUPLICATE KEY UPDATE `log_text`='{$text}',`status_id`='{$status}';
SELECT LAST_INSERT_ID() as id;
")->execute();
} catch(\Database_Exception $e) {
return array(false, \DBE::handle_error());
}
return array(true, $log_query);
}
Can anybody see, what's wrong?
Thanks for any answer.
separate the insert from the update that will fix it
In order to get the right result you'll have to supply the query type in this case because it's not designed to do super smart result type detection based on the query. I think your query should work when you supply the following second parameter:
$result = \DB::query($query, \DB::SELECT);
This should give you a Result object from which you can get the id.

Update query insert zero in table in ci

Update query insert zero in table everytime.
I have prtinted the query.From phpmyadmin the lastquery working fine.updated with same value
But when db active query then it has updating 0.
tbl_setitbl
set_id(primary key)
reference(text)`
Here is my code.
public function edit_set($id,$setvalue)
{
$data = array('reference' => $setvalue);
$this->db->where('set_id', $id);
$this->db->update('tbl_setitbl', $data);
if($this->db->affected_rows())
return true;
else
return false;
}
I have tried this code also.
$this->db->where('set_id', $id);
$this->db->update('tbl_setitbl', array('reference' => $setvalue));
echo $this->db->last_query();
UPDATE tbl_setitbl SET reference = 'hhhhhhhh' WHERE set_id = 1
Sorry every one...
Get solved
actually the problem is in controller.
query has run two times as redirection has not doing properly
see the result by using $this->db->last_query() then verify the sql code if it is similiar to the sql code that you have tried in phpmyadmin

how to get last inserted record in symfony1.4

how to get last inserted record in symfony1.4
i do not have much knowledge of symfony.
and i need the the id of last inserted record in symfony1.4, so If you have any idea please let me know.
public function executeAddquestion(sfWebRequest $request)
{
$q=$this->getUser()->getAttribute('quiz');
$qs=$this->getUser()->getAttribute('questions');
$t = new test();
$t->setTestName($q);
$t->setTestQuestions($qs);
$t->save();
$t->getId();
}
the above code, which can i tried. but not got anything.
so please help me.
You are getting the id but not storing it anywhere?
Try the following:
$lastId = $t->getId();

Get the last id before insert ZF2

I am trying to implement an action that can get me the last inserted id before I insert a record.
The action is basically supposed to get the last inserted id, then i add 1 to it then the value will be used in the current data been inserted.
This how far I have gotten and the error am getting
//the action to get the last inserted id
public function getLastID(){
$lastcourseid = $this->tableGateway->select(function (Select $select){
$select->columns(array('id'));
$select->order('id ASC')->limit(1);
});
var_dump($lastcourseid);
return $lastcourseid;
}
I call the function here before saving
if($id == 0){
$data['course_code'] = $this->getLastID();
$this->tableGateway->insert($data);
}else{
if($this->getAlbum($id)){
$this->tableGateway->update($data, array('id' => $id));
}else{
throw new \Exception("Form id does not exist");//an error is thrown in case the id is not found
}
}
This is the error am getting
Catchable fatal error: Object of class Zend\Db\ResultSet\ResultSet
could not be converted to string
I do not know where am going wrong.
Any help will be appreciated. Thanks
There is no such thing like "last id before insert".
And you don't need it.
First insert a record and then get your id. This is how it works.
You do not mention the underlying database (postgressql, mysql, etc.). I am more familiar with MySQL. The Perl and php AIP's have "last row id" functions. For example, php has "mysqli_insert_id()". This assumes that your rowID is an AUTO_INCREMENT column. Other DBs may have different requirements.

Categories