简体   繁体   中英

How do I get the “ID” number from a mysql record and use it to update that record using php?

Here is my test form (link to form removed) if you click on the update ticket link it will bring you to a page to add additional information to the record. I see the id for that record passed to the form in the browser url as the end of the url says ?id=10 or whatever the id number for that record is. This is where I'm stuck, I can't get the record to update, I input the info in the form and click the update button and it tells me it added 1 record but it doesn't add the info to MySQL and I don't get any errors either. so here is the code I'm using to update the record:

<?php

include 'db_connect.php';

$city=$_POST['city'];
$state=$_POST['state'];
$zip=$_POST['zip'];
$id=$_REQUEST['id'];

 mysql_query("UPDATE `test` SET 
                                 `city` = '$city',
                                 `state` = '$state',
                                 `zip` = '$zip',
                           WHERE `id` = '$id'") 

?>

I added a hidden input field to my form with the name of 'id' thinking that was what was wrong but no change. What am I doing wrong? what do I need to do to pass the id? Thanks!

Adding the code for my update form:

<html>
<body>

<form action="update.php" method="post">
<input type="hidden" name="id" value="<?php echo $_GET['id']; ?>">
City <input type="text" name="city">
State<input type="text" name="state">
Zip <input type="text" name="zip">
<input type="submit" value="update">
</form>

</body>
</html> 

Revised update code:

<?php

include 'db_connect.php';

$city=$_POST['city'];
$state=$_POST['state'];
$zip=$_POST['zip'];
$id=$_POST['id'];




 mysql_query("UPDATE `test` SET      `city` = '$city', `state` = '$state', `zip` = '$zip' WHERE `id` = '$id'");



?>

You need to post id with the form.

//Add this hidden field inside form to store and post id
<input type="hidden" name="id" value="<?php echo $_GET['id']; ?>"/>

The id gets lost when form is posted. so we need to store it and send it with the form.

// remove the comma before where in this line
mysql_query("UPDATE `test` SET      `city` = '$city', `state` = '$state', `zip` = '$zip' WHERE `id` = '$id'");

You are passing id by GET method. so use $_GET['id] to get id. Assign this id to a hidden field. Like: <input type="hidden" name="id" value="<?php echo $_GET['id']; ?>"/>

In update page. $id=$_POST['id'];//get id value by post method

 mysql_query("UPDATE `test` SET      `city` = '$city', `state` = '$state', `zip` = '$zip', WHERE `id` = '$id'");

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM