My SQL triggers

Is it possible to configure a mysql trigger that returns the id number of this record when there is ever an insert into the database And how can I capture it with php?

+3
source share
4 answers

If I do not fully understand your question, you do not need a trigger for this - just use the "last inserted identifier" functionality of your database driver.

Here is an example using the base mysql driver in PHP.

<?php

$db = mysql_connect( 'localhost', 'user', 'pass' );

$result = mysql_query( "insert into table (col1, col2) values ('foo', 'bar')", $db );

$lastId = mysql_insert_id();

This is a secure connection method for obtaining an identifier.

+3
source

, . mysql_insert_id(), [documentation] [1].

, insert , NEW. [identity_column_name] :

CREATE TABLE temp (
    temp_id int auto_increment,
    value varchar(10),
    PRIMARY_KEY(temp_id)
);

CREATE TRIGGER after_insert_temp AFTER INSERT ON temp
FOR EACH ROW 
BEGIN
    DECLARE @identity;
    SET @identity = NEW.temp_id;
    -- do something with @identity
END
+2

, . , ? ,

printf ( " id% d\n", mysql_insert_id());

+1
0

Source: https://habr.com/ru/post/1703134/


All Articles