Take a line ID that has just been created in PHP

Asked

Viewed 958 times

4

Hey, guys, let’s go So I’m having a problem which is this, I have a table players, a table workouts and an auxiliary table playfulness (where I’ll see if any players are training at the moment) The point is, how can I make it so that when I create a workout, this auxiliary table is populated with the training ID I just created and the players id. For example, in my interface I select a practice and select players who will participate, by clicking on the "Start training" button I want, in addition to creating a column in the table workouts, with auto-increment ID, I want you to create in the table playfulness a line with the ID that has just been generated. I hope I illustrated it well haha. In java it would be using Statement.RETURN_GENERATED_KEYS, but in PHP I no longer manjo. Someone knows how to do?

  • 2

    What extension is used in PHP to interact with DB?

  • Want to get the last id inserted in that table this? vc need to tell which API is using for connection in the database.

  • 1

    @Bacco I am using PDO connection

2 answers

8


If you are using the Mysqli extension:

mysqli_query( $con,"INSERT INTO jogadores(nome, idade) VALUES ('Pedro',35)" );
$id = mysqli_insert_id( $con ); // Aqui obtemos o ID do registro inserido

For PDO:

$id = $con->lastInsertId();

If you are using the Mysql extension, what is not recommended:

$id = mysql_insert_id();
  • Thanks, I knew it was something simple haha. Really worth!

  • 1

    @Luangabriel please mark the answer as accepted.

2

You can use the following SQL:

SELECT LAST_INSERT_ID() as id FROM tabela

Browser other questions tagged

You are not signed in. Login or sign up in order to post.