Adding Record In Database Using PHP

by Hiroshi on June 19, 2008

in MySQL, php mySQL

Create a file index.php and insert.php. Also create a DataBase with some name lets say mydb in mysql. After creating database named as mydb add a table named as mydbtb in it with four fields. If you do not know about mysql then just open it and create a database mydb in it and run this query in it from query window.

CREATE TABLE IF NOT EXISTS `mydbtb` (
  `id` int(11) NOT NULL auto_increment,
  `name` varchar(199) NOT NULL default '',
  `password` varchar(199) NOT NULL default '',
  `email` varchar(199) NOT NULL default '',
  PRIMARY KEY  (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=1 ;

Now add the following code in your PHP files. It must add some data in database.

index.php Coding

<form name="frmInsert" method="post" action="insert.php">
	<table>
		<tr>
			<td>Name</td>
			<td><input type="text" name="txtName"></td>
		</tr>
		<tr>
			<td>Password</td>
			<td><input type="password" name="txtPassword"></td>
		</tr>
		<tr>
			<td>Email</td>
			<td><input type="text" name="txtEmail"></td>
		</tr>
		<tr>
			<td colspan="2"><input type="submit" value="Submit"></td>
		</tr>
	</table>
</form>

insert.php Coding

<?php
$sDbUserName = "root";
$sDbPassword = "";
$sDatabase = "mydb";
 
	$dbConnection = @mysql_connect("localhost", $sDbUserName, $sDbPassword);
	if (!$dbConnection)
	{
		echo "Unable to connect to the database server at this time.";
		exit( );
	}
 
	if (!@mysql_select_db($sDatabase, $dbConnection))
	{
		echo "Unable to locate the database at this time.";
		exit( );
	}
 
	$sName = $_REQUEST["txtName"];
	$sPassword = $_REQUEST["txtPassword"];
	$sEmail = $_REQUEST["txtEmail"];
 
	$sInsertQuery = "INSERT INTO mydbtb VALUES('', '$sName', '$sPassword', '$sEmail')";
	if (!mysql_query($sInsertQuery))
	{
		print mysql_error();
		mysql_close();
 
	}
	else
	{
		print "Record Added";
		mysql_close();
 
	}
?>

Add In Database Script Download

Related Posts

Previous post:

Next post: