Receive POST ID and play to Location via GET

Asked

Viewed 578 times

1

I need to get the ID of the entity that has just been registered. Only it will be played to another screen, to be registered other information. I would like to know how I can get the entity ID when saving the form.

This is the HTML

<form action="set.php" method="post">

	 <div class="col-md-6">
		 <div class="form-group">
			<label class="control-label">*Nome</label>
			<input type="text" id="nome" name="nome" class="form-control" placeholder="">
		 </div>
     </div>
     <div class="col-md-6">
		<div class="form-group">
			<label class="control-label">Sobrenome</label>
			<input type="text" id="sobrenome" name="sobrenome" class="form-control" placeholder="">
		</div>
	 </div>

And this is PHP

<?php

$nome                = $_POST ["nome"];  
$sobrenome           = $_POST ["sobrenome"]; 

$sql = mysql_query ("INSERT INTO gr_entidade (nome, sobrenome ) VALUES ('$nome', '$sobrenome')");

header("Location: usuario?id=id");
?>

header("Location: usuario?id=id");

Can you give me a hand ?

  • mysql_insert_id - Gets the ID generated by the previous INSERT operation http://php.net/manual/en/function.mysql-insert-id.php

  • LAST_INSERT_ID - only works if you made the last insertion on the same connection. If the last insert added 3 records in DB, this function returns the first of them, not the last. https://answall.com/questions/127456/forma-otimizada-recuperar-ultimo-id-mysql

  • Do header("Location: outrapagina.php?id=" . mysql_insert_id()); and on the other page receive so <div><?php echo $_GET['id']; ?></div>

2 answers

1

To capture the last added ID, just run the sql query.

mysql_query("SELECT LAST_INSERT_ID()");

Or you can use the function mysql_insert_id

  • Thanks. I used the function mysql_insert_id and it worked

1


According to PHP documentation:

Use: mysql_insert_id().

Ex.:

<?php

$nome                = $_POST ["nome"];  
$sobrenome           = $_POST ["sobrenome"]; 

$sql = mysql_query ("INSERT INTO gr_entidade (nome, sobrenome ) VALUES ('$nome', '$sobrenome')");

$last_id = mysql_insert_id();

header("Location: usuario?id=$last_id");
?>

It is worth noting that the extension mysql is obsolete according to the same documentation:

Warning This extension has been deprecated since PHP 5.5.0 and has been removed from PHP 7.0.0. Use Mysqli or Pdo_mysql alternatively. See also Mysql: choosing a related API and Faqs for more information. Alternatives to this function include:

mysqli_insert_id()

PDO::lastInsertId()

It is recommended to migrate to extensions mysqli or PDO.

Browser other questions tagged

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