MySQL: Can't get LAST_INSERT_ID() - php

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.

Related

Sqlite does not return correct primarykey in php [duplicate]

Is there any built in function available in SQLite to fetch last inserted row id.
For eg :- In mysql we have LAST_INSERT_ID() this kind of a function. For sqllite any function available for doing the same process.
Please help me.
Thanks
SQLite
This is available using the SQLite last_insert_rowid() function:
The last_insert_rowid() function returns the ROWID of the last row
insert from the database connection which invoked the function. The
last_insert_rowid() SQL function is a wrapper around the
sqlite3_last_insert_rowid() C/C++ interface function.
PHP
The PHP version/binding of this function is sqlite_last_insert_rowid():
Returns the rowid of the row that was most recently inserted into the
database dbhandle, if it was created as an auto-increment field.
When Using SQLite version 3 with PDO SQLite, It can be like this:
$insert = "INSERT INTO `module` (`mid`,`description`) VALUES (
NULL,
:text
);
";
$stmt = $conn->prepare($insert);
$stmt->execute(array(':text'=> $text));
echo $conn->lastInsertId()
It has last_insert_rowid()
The last_insert_rowid() function returns the ROWID of the last row
insert from the database connection which invoked the function
sqlite_last_insert_rowid(resource $dbhandle)
This is a short C# method that is working for me. Int32 is large enough for my purposes.
public static Int32 GetNextID( SqliteConnection AConnection )
{
Int32 result = -1;
using ( SqliteCommand cmd = AConnection.CreateCommand() )
{
cmd.CommandText = "SELECT last_insert_rowid();";
using ( SqliteDataReader r = cmd.ExecuteReader() )
{
if ( r.Read() )
result = (Int32) r.GetInt64( 0 );
}
}
return result;
}
I'm new to SQLite and this thread is quite old so I thought it may need an update as I feel there is a simpler and shorter method of getting the 'id' of the last inserted row. I used ->querySingle() instead of ->exec() and included at the end of my SQL statement returning id.
I feel this is probably more reliable and thread-safe since it's the result of the actual insert statement. Maybe even lighter processing on resources.
$id = $db->querySingle("insert into names (first, last) values ('john', 'do') returning id;");

How to print exact sql query before execute in Zend Framework 2

I am working on an application using Zend framework 2. I'm using TableGateway to select, insert, update and delete query.
1. My question is how to print exact sql query before executing INSERT, UPDATE and DELETE statement? For SELECT statement here is my code which is working for me.
$selectedTable = new TableGateway($this->tblName, $this->dbAdapter);
$sql = $selectedTable->getSql();
$select = $sql->select();
if ($trace) {
echo "<br>" . $sql->getSqlstringForSqlObject($select) . "<br>";
exit;
}
else {
$resultSet = $selectedTable->selectWith($select);
unset($selectedTable);
return $resultSet;
}
2. For last inserted id I'm using this code and working fine.
$selectedTable = new TableGateway($this->tblName, $this->dbAdapter);
$selectedTable->insert($dataArray);
$insertId = $selectedTable->adapter->getDriver()->getConnection()->getLastGeneratedValue();
unset($selectedTable);
return $insertId;
But for UPDATE how to get last updated id? and for DELETE how to get affected row? Because for UPDATE and DELETE this code is not working.
Can anyone suggest how to do these job?
1. There should be no difference nor difficulties, do it exaclty the same way on your $insert object. Here how I perform Sql insert and get the SQL string:
$sql = new Sql($this->dbAdapter);
$insert = $sql->insert('table');
[...]
$sqlString = $insert->getSqlString($this->dbAdapter->getPlatform());
2. When you insert a value, you do not know what will be the generated value id before insertion, but you will only know it ater insertion. That's why there is the getLastGeneratedValue-) method for inserted values.
But when you update or delete a value, its id is already defined and you can read it. So all you have to do is to read it from your database. Perform a select before updating or deleting your(s) objetct(s) and you will know all the ids you want.

Return primary key for the inserted row (PHP adn SQLite)? [duplicate]

Is there any built in function available in SQLite to fetch last inserted row id.
For eg :- In mysql we have LAST_INSERT_ID() this kind of a function. For sqllite any function available for doing the same process.
Please help me.
Thanks
SQLite
This is available using the SQLite last_insert_rowid() function:
The last_insert_rowid() function returns the ROWID of the last row
insert from the database connection which invoked the function. The
last_insert_rowid() SQL function is a wrapper around the
sqlite3_last_insert_rowid() C/C++ interface function.
PHP
The PHP version/binding of this function is sqlite_last_insert_rowid():
Returns the rowid of the row that was most recently inserted into the
database dbhandle, if it was created as an auto-increment field.
When Using SQLite version 3 with PDO SQLite, It can be like this:
$insert = "INSERT INTO `module` (`mid`,`description`) VALUES (
NULL,
:text
);
";
$stmt = $conn->prepare($insert);
$stmt->execute(array(':text'=> $text));
echo $conn->lastInsertId()
It has last_insert_rowid()
The last_insert_rowid() function returns the ROWID of the last row
insert from the database connection which invoked the function
sqlite_last_insert_rowid(resource $dbhandle)
This is a short C# method that is working for me. Int32 is large enough for my purposes.
public static Int32 GetNextID( SqliteConnection AConnection )
{
Int32 result = -1;
using ( SqliteCommand cmd = AConnection.CreateCommand() )
{
cmd.CommandText = "SELECT last_insert_rowid();";
using ( SqliteDataReader r = cmd.ExecuteReader() )
{
if ( r.Read() )
result = (Int32) r.GetInt64( 0 );
}
}
return result;
}
I'm new to SQLite and this thread is quite old so I thought it may need an update as I feel there is a simpler and shorter method of getting the 'id' of the last inserted row. I used ->querySingle() instead of ->exec() and included at the end of my SQL statement returning id.
I feel this is probably more reliable and thread-safe since it's the result of the actual insert statement. Maybe even lighter processing on resources.
$id = $db->querySingle("insert into names (first, last) values ('john', 'do') returning 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

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