Get the last id before insert ZF2 - php

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.

Related

Getting null when using getLastInsertID in cakephp2.10

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();

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.

Customized search need to display name search result based on selected name

I Implemented my project in Yii. i showing search results. based on differed table and different field value from table. it displaying very well.
i sent from controller post values and displaying values in view part.
it displaying only the id if i give name its not displaying and showing error. i added my code here. just check and tell where i need to be change accordingly my code.
<?php
if(isset($getval)){
$as=$getval;
}else{
$as="";
}
if(isset($course)){
$as1=$course;
}else{
$as1="";
}
if(isset($type)){
$as3=$type;
}else{
$as3="";
}
if(isset($cuisine)){
$as4=$cuisine;
}else{
$as4="";
}
if(isset($calorie)){
$as5=$calorie;
}else{
$as5="";
}
<?php
echo '<p align="center"> Showing results for&nbsp:&nbsp'.'Name'.$getval.',&nbsp'.'Course-'.$course.',&nbsp'.'Cuisine-'.$cuisine.',&nbsp'.'Type-'.$type;',&nbsp';'</p>';
echo ',&nbsp'.'Calories-'.$calorie;
its working fine and displying only id :
if i give like this id to concern table values name not displaying
$query= Course::model()->find("course_id=$as1");
$course2=$query['course_name'];
$query1= Cuisine::model()->find("id=$as4");
$cuisine2=$query1['cuisinename'];
$query3= RecipeType::model()->find("id=$as3");
$type2=$query3['recipeType_name'];
please suggest my suitable answer
I'm not sure if I undertand your question, but, the find method return a CActiveRecord object with the first value who matches the condition.
Accessing to a column (field) is done by the "magic" properties of the object. There's a property for each column, so you can access to the 'course_name' column this way:
$query= Course::model()->find("course_id=$as1");
$course2=$query->course_name;
See This guide, specially the "Reading record" section
$Criteria = new CDbCriteria;
$Criteria->compare('course_id',$as1);
$query= Course::model()->find($Criteria);
if(!empty($query))
$course2=$query->course_name;
$post=Post::model()->find('postID=:postID', array(':postID'=>10));
http://www.yiiframework.com/doc/guide/1.1/en/database.ar

Incorrect value written to mysql database

I am trying to write a value to a database. Everything seems to be fine except one value is mysteriously incorrect. I just can't figure this out.
Using codeigniter here is my controller:
$sample_id = $this->input->post('sample_id');
$culture_id = $this->input->post('culture_id');
$sample_name = $this->vial_model->get_name($culture_id);
$box_id = $this->input->post('boxid');
$db_data['boxid'] = $box_id;
$db_data['taskid'] = $sample_id;
$db_data['projectid'] = $culture_id;
$vial_id = $this->vial_model->create($db_data);
$vial_link = '<a href="'.base_url('freezer_vial/view/'.$culture_id.'/'.$sample_id.'/'.$vial_id).'" >'.$sample_name.'</a>';
Lets imagine that the value for $sample_id is 158 (or any number really) and that I can echo this value to the view to confirm.
The anchor link that is output to the view is as expected and contains 158. However, the value for $db_data['taskid'] is always 127 and is inserted into the database as this. I have no idea why. Everything else works fine.
Here is the model:
public function create($data)
{
$insert = $this->db->insert('vial', $data);
if($insert)
return $this->db->insert_id();
else
return false;
}
The column in your database table holding the sample id value might have been defined as a tinyint. See also https://stackoverflow.com/a/16684301/282073.
You might want to alter the column type to ensure no data is altered for each new insertion or update. Instances can be found in another answer https://stackoverflow.com/a/13772308/282073
Official documentation to alter tables can be read from
http://dev.mysql.com/doc/refman/5.1/en/alter-table.html

mysql_insert_id() returns 0

I know there are a lot of topics with the same title. But mostly it's the query that's been inserted in the wrong place. But I think I placed it right.
So the problem is, that I still get 0 even when the data is inserted in the db.
Does someone knows an answer where I could be wrong?
here's my code:
mysql_query('SET NAMES utf8');
$this->arr_kolommen = $arr_kolommen;
$this->arr_waardes = $arr_waardes;
$this->tabel = $tabel;
$aantal = count($this->arr_kolommen);
//$sql="INSERT INTO `tbl_photo_lijst_zoekcriteria` ( `PLZ_FOTO` , `PLZ_ZOEKCRITERIA`,`PLZ_CATEGORIE`)VALUES ('$foto', '$zoekje','$afdeling');";
$insert = "INSERT INTO ".$this->tabel." ";
$kolommen = "(";
$waardes = " VALUES(";
for($i=0;$i<$aantal;$i++)
{
$kolommen .=$this->arr_kolommen[$i].",";
$waardes .="'".$this->arr_waardes[$i]."',";
}
$kolommen = substr($kolommen,0,-1).")";
$waardes = substr($waardes,0,-1).")";
$insert .=$kolommen.$waardes;
$result = mysql_query($insert,$this->db) or die ($this->sendErrorToMail(str_replace(" ","",str_replace("\r\n","\n",$insert))."\n\n".str_replace(" ","",str_replace("\r\n","\n",mysql_error()))));
$waarde = mysql_insert_id();
Thanks a lot in advance, because I have been breaking my head for this one for almost already a whole day. (and probably it's something small and stupid)
According to the manual mysql_insert_id returns:
The ID generated for an AUTO_INCREMENT column by the previous query on
success, 0 if the previous query does not generate an AUTO_INCREMENT
value, or FALSE if no MySQL connection was established.
Since it does not give you false and not the correct number it indicates that the queried table didn't generate an auto-increment value.
There are two possibilities I can think of:
Your table doesn't have an auto_increment field
Since you doesn't provide the link to the mysql_insert_id() but using a link with mysql_query() it might not be the correct table that's queried when retrieving the last inserted id.
Solution:
Make sure it has an auto_increment field
Provide the link aswell: $waarde = mysql_insert_id($this->db);
It is possible that your INSERT query was not successful - e.g., maybe you were trying to insert duplicate data on a column whose data must be unique?
If the id is indeed set to auto increment and still get '0' as your response do a column and value count i experienced this only later on I noticed a number of my column count did not match values count.
Codeigniter has an odd behaviourd when calling mysql_insert_id(). The function returns 0 after the first call. So calling it twice will return 0.
Use a variable instead of calling the function more times:
$id = mysql_insert_id();

Categories