How do I get the last insert id from a database using a ODBC connection?
I'm looking for a solution similar to the mysql_insert_id() function.
SELECT ##IDENTITY AS ID
If you're using databases with PHP I strongly recommend using PDO (simple database wrapper for a lot of common database engines, more and more supported all the time, part of PHP canon), and hence use PDO::lastInsertId if your database supports the equivalent of mysql_insert_id.
Don't use "SELECT max(id) FROM table;" as it can result in seriously freaky and hard-to-find bugs later on.
* **UPDATE : Ok, you're using ODBC, and I suspect you're after odbc_cursor. I still stand by the strong recomendation to use PDO, as it has an ODBC driver. (ODBC in my eyes is an grumpy bitter old man who mumbles under his breath driving his truck that's falling apart, as the hip and effective PDO guys race past in their sexy VOLVO S90's)
It depends on the database type, but look into the SEQUENCE syntax for your rdbm.
I used "SELECT ##IDENTITY AS LastID", while working with PHP/MSSQL, through ODBC. That brought some issues under SQL 2005 server (or was it 2000?).
Either way if you do like this:
SET NOCOUNT ON
[NOW INSERT YOUR INSERT SQL QUERY]
SELECT ##IDENTITY AS LastID
you should be just fine in any MSSQL server version.
"SET NOCOUNT ON" will prevent sql server from sending messages like '1 rows inserted', which will keep your script working properly.
If you have MySQL under ODBC - you can use the next query:
"SELECT LAST_INSERT_ID( );"
It have to be executed mmediately after executing INSERT-query.
For other database - use other specific queries...
Use in MySQL
SELECT *
FROM table_name
ORDER BY Id Desc
LIMIT 1
Use in SQL Server
SELECT top 1 *
FROM table_name
ORDER BY Id Desc
Are you inserting rows into your database via PHP? If so, perhaps you can generate a unique primary key using uniqid() - then you will know the ID without having to query the database.
If it is not possible to update the key type, perhaps you can still insert a unique id when you do the inserts, so you could do a query like this:
SELECT id FROM mytable WHERE rowid = '$myuniqueid'
That way you're ensuring that you're pulling back the correct ID from the database - a much better solution than MAX(id).
Using
SELECT max(id) FROM table;
should be fine from inside a transaction, or does ODBC not support transactions?
Related
This is my first time using T-SQL
I am currently trying to get the last inserted ID from an INSERT statement in T-SQL using this query:
INSERT INTO TICKET( STATE, RECORD_DATE, ID_USER, TICKET_TYPE, TICKET_COM)
OUTPUT INSERTED.ID_TICKET AS lastId
VALUES ( 1, CONVERT(datetime, '24/02/2022 09:25:53'), 100, 1, 'It does not work')
As you've guessed, ID_TICKET is the identity, with auto_increment.
When I run this through MS SQL server management studio, I get the intended result : one row, with a unique lastId column containing the value of the last inserted id.
However on PHP, when I am running this using the query() method from PEAR database, I am running into some issue.
From reading the documentation, DB->query() will only return a resource in case of a SELECT query, while an INSERT query will just return a DB_OK type of answer: which is exactly what I am getting in PHP.
Hence my question : how can I retrieve the OUTPUT from an INSERT statement with PEAR DB?
I'd like to continue using PEAR, as I am adding functionality to an existing intranet heavily relying on it.
It is hosted on IIS 7 with SQL Server 9.0 using PHP 5.2.9 and PEAR DB 1.1.2.2.
Finally, I just did a simple INSERT by removing the OUTPUT INSERTED.ID_TICKET AS lastId line.
I then did a second query() call immediately after : SELECT ##IDENTITY as lastId and it now gives the desired results.
Pretty much what Álvaro González suggested.
Now, following Dan Guzman sugestion and adding SET NOCOUNT ON; at the beggining of my original INSERT with the OUTPUT clause indeed solved the problem !
I now get a result set with a unique row and column lastId as desired.
My hat off to both of you.
I am inserting values in a table but it's not working in sequence, see screenshot:
Code:
$query = "insert into msgs values(NULL,'".$sender."','".$receiver."','".$message."','".$state."','".$time."')";
mysql_query($query);
First of all don't use mysql, use mysqli. Please check this: The mysql extension is deprecated and will be removed in the future: use mysqli or PDO instead
Using null when inserting autoincrement is fine (see Devon's first comentary).
When looking at your timestamp (msg_time) i can see that your table is short by another column because they are not in order anyway. This is only an visual shorting and don't affect entries structure, so don't worry.
Hello im developing an application where data comes from MSSQL database. Here using php odbc connection i get all the needed data to work with app. But now i have a problem:
Im looking for:
All data from mssql (assume) mssql_Table_A will be listed in this app, each row will be given with checkbox so user can check the data required, after checking When he hit save checked data will be stored in local MySQL database (assume) mysql_table_A.
So next time when he again wants few more data, this app will list all the data from mssql_table_A which dont exists in mysql_table_A.
Problem is:
If both the dataflwo were from MYSQL i would have done this where easily by using mysql select query
mysql_query("SELECT * FROM mysql_table_a WHERE NOT EXISTS (SELECT * FROM mysql_table_B WHERE thisID != thatID)")
But here how do i check data exists in mysql table and list the data from odbc mssql database.
Please help me to resolve this problem.
Thank You..
You need to use mssql_, sqlsrv_ or PDO functions to connect to MSSQL. mysql_ functions are strictly for MySQL.
Microsoft SQL Server Driver for PHP
Microsoft SQL Server
Microsoft SQL Server Functions (PDO_SQLSRV)
You will need two separate connections if you are fetching data from both.
Alternatively, you can connect to MySQL from MSSQL using an ODBC connection and perform your query on the MSSQL side.
The other answers have told you how to connect the two databases but based on your comments you still want to know how to do the comparison.
I have to assume you've got at least one column which you can uniquely identify rows in table_a which are not in table_b. If you link mysql in MS SQL Server like one answer said you can
select * from mssql.table_a where unique_column not in (select unique_column from mysql.table_b)
but this works because mssql is linked to mysql in mssql i.e., you can do one query and mssql will do the join for you.
If for some reason you cannot or don't want to link mysql to ms sql via a linked table the easiest way would be if you had some sort of timestamp in table_a. Let's say every record written into table_a has a timestamp of when it was inserted:
mysql connection does select max(timestamp) into X from mysql.table_b
mssql connection does select * from mssql.table_a where timestamp > X
There may be other ways if we knew a bit more about your data.
I have a SQL table gathering form results. I noticed after about 200 results had been gathered, that instead of the date being in the format of 2011-06-01, that it was in the format of 2011-6-01, skipping the leading zero. This is giving some data processing problems. Is there a way to update all the 2011-6-xx values to make then 2011-06-xx? Solutions in either PHP/MySQL or just MS-SQL statements are acceptable, as the data is collected on a webserver using a PHP/MySQL form, exported to CSV, and then imported into an MS-SQL database on site for data analysis.
UPDATE `table` SET `date_column` = REPLACE(`date_column`, '2011-6-', '2011-06-') WHERE `date_column` LIKE '2011-6-%';
UPDATE Table1
SET field1 = REPLACE(field1, '2011-6-', '2011-06-')
WHERE field1 LIKE '2011-6%'
The where will allow you to use an index and replace much faster than looking through all rows.
Also in strict mode MySQL will not execute UPDATE statements without a where clause.
You talk about MS-SQL and MySQL. If it's MS SQL, then the below should work. I don't know if MySQL uses REPLACE or has an equivalent function.
UPDATE
Some_Table
SET
some_string = REPLACE(some_string, '2011-6-', '2011-06-')
WHERE
some_string LIKE '2011-6%'
Im wondering if the way i use to retrieve the id of the last row inserted in a postgresql table is efficent..
It works, obviously, but referencing on the serial sequence currval value could be problematic when i have many users adding rows in the same table at the same time.
My actual way is:
$pgConnection = pg_connect('host=127.0.0.1 dbname=test user=myuser password=xxxxx')or die('cant connect');
$insert = pg_query("INSERT INTO customer (name) VALUES ('blabla')");
$last_id_query = pg_query("SELECT currval('customer_id_seq')");
$last_id_results = pg_fetch_assoc($last_id_query);
print_r($last_id_results);
pg_close($pgConnection);
Well, its just a test atm.
But anyway, i can see 3 issues with this way:
Referencing on the customer_id_seq, if two user do the same thing in the same time, could happen that them both get the same id from that way... or not?
I have to know the table's sequence name. Becose pg_get_serial_sequence dont works for me (im newbie on postgresql, probably is a configuration issue)
Any suggestion/better ways?
p.s: i can't use the PDO, becose seem lack a bit with the transaction savepoint; I wont use zend and, in the end, i'll prefer to use the php pg_* functions (maybe i'll build up my classes in the end)
EDIT:
#SpliFF(thet deleted his answer): this would works better?
$pgConnection = pg_connect('host=127.0.0.1 dbname=test user=myuser password=xxxxx')or die('cant connect');
pg_query("BEGIN");
$insert = pg_query("INSERT INTO customer (name) VALUES ('blabla')");
$last_id_query = pg_query("SELECT currval('customer_id_seq')");
$last_id_results = pg_fetch_assoc($last_id_query);
print_r($last_id_results);
//do somethings with the new customer id
pg_query("COMMIT");
pg_close($pgConnection);
If you use a newer version of PostgreSQL (> 8.1) you should use the RETURNING clause of INSERT (and UPDATE) command.
OTOH if you insist on using one of the sequence manipulation functions, please read the fine manual. A pointer: "Notice that because this is returning a session-local value, it gives a predictable answer whether or not other sessions have executed nextval since the current session did."
Insert and check curval(seq) inside one transaction. Before commiting transaction you'll see curval(seq) for your query and no matter who else inserted at the same time.
Don't remember the syntax exactly - read in manual (last used pgsql about 3 years ago), but in common it looks like this:
BEGIN TRANSACTION;
INSERT ...;
SELECT curval(seq);
COMMIT;
ex. minsert into log (desc,user_id) values ('drop her mind',6) returning id