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')" ; 

Overview

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

Steps

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 '',
PRIMARY KEY (`id`)
);

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


Creating a file insert_ac.php

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


<?php
$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");
$name=$_POST['name'];
$country=$_POST['country'];
$email=$_POST['email'];
$sql="INSERT INTO $tbl_name(name, country, email)VALUES('$name', '$country', '$email')";
$result=mysql_query($sql);
if($result){
echo "Successful";
}
else {
echo "ERROR";
}
mysql_close();
?>