Ross Taylor
Ross Taylor

Reputation: 109

Inserting values into form fields --PHP

I get values from an HTML form using a post method and store them in my DB through the mysql INSERT command (done in PHP).

something like this:

$value = $_POST['name'];
$value1 = $_POST['age'];
$sql = "INSERT INTO table(name,age) VALUES('$value','$value1')" ;

Now what I want to do is I want to give a link in the same PHP file like:

echo '<A HREF="http://xxx.com/rascal.php/">To update just entered info click on me</a>';

Now the rascal.php as mentioned in the link above also contains the same form fields (name and age).

The values stored in the database through the INSERT command above should be fetched from the DB and placed in the respective form field area (name and age should be stored in their respective forms of rascal.php).

How can I do this?

Upvotes: 1

Views: 8620

Answers (2)

JanLikar
JanLikar

Reputation: 1306

Here it is:

<?php

if(isset($_GET['name']) AND isset($_GET['age'])){
$name=$_GET['name'];
$age=$_GET['age'];
}
else{
if(!empty($_POST['name']) AND !empty($_POST['age'])){

$value=mysql_real_escape_string($_POST['name']);
$value1=mysql_real_escape_string($_POST['age']);
$sql = "INSERT INTO table(name,age) VALUES('$value','$value1')" ;
mysql_query($sql);

echo '<A HREF="http://xxx.com/rascal.php?name='.$value.'&age='.$age.'">To update just entered info click on me</A>';
}
}

?>

<form method="POST">
<input name="name" value="<?php print $name;?>"/>
<input name="age" value="<?php print $age;?>"/>
</form>

This should work if you change 'table' to your table name. You should be happy, because I wrote the entire code for you. Please show it.

Further advice: Make sure your code is save by passing all input variables through a mysql_real_escape_string() function. Add an id field (unique key, self incrament) to your database table so you can select records based on their id's and not some other field (The code I provided only works if you don't have more entries with the same name).

There are some great php tutorials here.

Upvotes: 2

Jeremy Morgan
Jeremy Morgan

Reputation: 3372

Bobby Jack is exactly right about the danger of this, but I'll try to answer your question anyway.

Why not do it without touching the database? You could modify the link to rascal.php like so:

echo '<A HREF="http://xxx.com/rascal.php?name=' . $value1 . '&age=' . $value2 .' /">To update just entered info click on me</a>';

And then use $_REQUEST['name'] to get that information in rascal.php. This way you are assured the same values are carried over.

Another way could be to use the mysql LAST_INSERT_ID and fetch the information that way, though it would not be 100% reliable, you could use that id for a query to populate the form as well.

EDIT: You could use LAST_INSERT_ID and put that id in the link for rascal.php, or use it in rascal.php itself to query the information you need.

Upvotes: 0

Related Questions