PHP Tutorials

Insert Data Into Mysql Using PHP

Hello Guys Welcome to Coding Gurus Online Portal ...!

As we have already created the databases and tables in the previous tutorials, we now learn how to insert data into that table using PHP Script.

Query to Use

 "INSERT INTO table_name(column_name1, column_name2)VALUES('value1, 'value2')" ; 


Here in this process we are going to create 2 files
1. insert.php
2. insert_conn.php


1. First we create a table coding in the database codinggurus.
2. Then we create file insert.php.
3. And then finally we create file insert_conn.php.

Query to Create A Table coding.

CREATE TABLE `coding` (
`id` int(10) NOT NULL auto_increment,
`name` varchar(50) NOT NULL default '',
`country` varchar(50) NOT NULL default '',
`email` varchar(50) NOT NULL default '',

Creating a file insert.php

Copy paste the below code to create a from through which we insert data into database.

<table width="300" border="0" align="center" cellpadding="0" cellspacing="1">
<td><form method="post" action="insert_ac.php">
<table width="100%" border="0" cellspacing="1" cellpadding="3">
<td colspan="3"><strong>Inserting Data Into Database </strong></td>
<td width="71">Name</td>
<td width="6">:</td>
<td width="301"><input name="name" type="text" id="name"></td>
<td><input name="country" type="text" id="lastname"></td>
<td><input name="email" type="text" id="email"></td>
<td colspan="3" align="center"><input type="submit" name="Submit" value="Submit"></td>

Creating a file insert_ac.php

The code below creates a conncetion between the form and the database.

$host="localhost"; // Host name
$username="coding"; // Mysql username
$password="coding"; // Mysql password
$db_name="codinggurus"; // Database name
$tbl_name="coding"; // Table name
// Connecting to server and select database.
mysql_connect("$host", "$username", "$password")or die("cannot connect");
mysql_select_db("$db_name")or die("cannot select DB");
$sql="INSERT INTO $tbl_name(name, country, email)VALUES('$name', '$country', '$email')";
echo "Successful";
else {
echo "ERROR";