Adscend

Click Here



Click Here



Click Here

Tuesday 3 September 2013

Insert Data Into a Database Table


Insert Data Into a Database Table




1.The INSERT INTO statement is used to add new records to a database table.
2.To execute INSERT INTO statement, we must use the mysql_query() function.

Syntax
INSERT INTO table_name
VALUES (value1, value2, value3,...)
Or
INSERT INTO table_name (column1, column2, column3,...)
VALUES (value1, value2, value3,...)

The first form doesn't specify the column names.
The second form specifies both the column names and the values to be inserted.

Example: 1
<?php

//Step 1: Create a Connection

$con mysql_connect("localhost","root","");
if (!
$con)
{
die(
"Could not connect: " mysql_error());
}
//Step 2: Create Database

$sql "CREATE DATABASE Aspell";

$retval mysql_query$sql$con);
if($retval )
echo 
"Database Aspell created successfully<br>";
else
die(
"Could not create database: " mysql_error());//Step 3: Select Current db

$db_selected mysql_select_db("Aspell"$con);
if (!
$db_selected) {
die (
"Can't select : " mysql_error());
}
//Step 4: Create Table

$sql "CREATE TABLE people
(
FirstName varchar(15) NOT NULL,
LastName varchar(15) NOT NULL,
Age int NOT NULL
)"
;//Step 5: Execute Query

$retval mysql_query($sql,$con);
if(! 
$retval )
{
die(
"Could not create table: " mysql_error());
}
echo 
"Table created successfully";//Step 6: Insert Data Into a Database Table

mysql_query("INSERT INTO people (FirstName, LastName, Age)
VALUES ('Oliva', 'Williamson',20)"
);mysql_query("INSERT INTO people (FirstName, LastName, Age)
VALUES ('Nicole', 'Cantwell',25)"
);mysql_close($con);

?>

Insert Data From a Form Into a Database
Example: 2
index.php
<html>
<body>
<form action="insert.php" method="post">
Firstname: <input type="text" name="firstname" />
Lastname: <input type="text" name="lastname" />
Age: <input type="text" name="age" />
<input type="submit" />
</form>
</body>
</html>

insert.php
<?php
$con 
mysql_connect("localhost","root","");
if (!
$con)
{
die(
"Could not connect: " mysql_error());
}
mysql_select_db("Aspell"$con);$sql="INSERT INTO people (FirstName, LastName, Age)
VALUES
('
$_POST[firstname]','$_POST[lastname]','$_POST[age]')";
if (!
mysql_query($sql,$con))
{
die(
"Error: " mysql_error());
}

echo "1 record added";mysql_close($con);?>