How to post a form to a database using php

September 17, 2007

Hi there reader,

This may be a trivial subject for many of you there but there are still peoples that can find it useful. So what I am talking here about?

The whole thing is about posting a form to a database using MySql + PHP. Suppose here you know how to create your database( using PhpMyAdmin most often). So we’ll use here a database called test and within it a table called test_table(name varchar(50),surname varchar(50)).

You will do the proposed thing in two steps: 1) creating the HTML form; 2) creating the PHP script that will handle it. The script can be saved in a separate file that will be put into the action=”" tag but i chose here to put into the same file for easiness.

So first, let’s build the HTML form:

<form method="post" action="<?=$_SERVER['PHP_SELF']?>">

 Name:<input name="name" type="text" />

Surname:<input name="surname" type="text" />

<input name="submit" value="Submit" type="submit" />

</form>

Save it as file.php for eg. Will look something like this

Name:


Surname:

Now add this before the form — the PHP handling script:

<?     /* if form posted processs it*/i(!empty($_POST['postform']))

{

/*connect to db*/

mysql_connect("localhost","user","pass");		  /* choose the db used*/

mysql_select_db("test");

/* transform $_POST['var'] to $var and mysql escape it */

foreach($_POST as $k=>$v)

$$k=mysql_escape_string($v);

$sql="insert into test_table(name,surname) values('$name','$surname'); ";

mysql_query($sql);

}

?>

For that to work, you have to mod user/pass/db_name,table_name with your own ones.

So finally you should have a file like this:

<?     /* if form posted processs it*/

i(!empty($_POST['postform']))

{

/*connect to db*/

mysql_connect("localhost","user","pass");		  /* choose the db used*/

mysql_select_db("test");

/* transform $_POST['var'] to $var and mysql escape it */

foreach($_POST as $k=>$v)

$$k=mysql_escape_string($v);

$sql="insert into test_table(name,surname) values('$name','$surname'); ";

mysql_query($sql);

}

?>

<form method="post" action="<?=$_SERVER['PHP_SELF']?>">

Name:<input type="text" name="name" value="" /><br />

Surname:<input type="text" name="surname" value="" /></br>

<input type="submit" name="postform" value="Submit"

</form>

Enjoy ;)

 

Post a comment

Name (required)

Mail (will not be published) (required)

Website

*
To prove you're a person (not a spam script), type the security text shown in the picture. Click here to regenerate some new text.
Click to hear an audio file of the anti-spam word