0
<html><head>
<title>Add record to my_database/my_table</title></head>
<body>

<?php


$self =  $_SERVER['PHP_SELF'];
$id =    $_POST['id'];
$fname = $_POST['fname'];
$lname = $_POST['lname'];


?>

<form action="<?php echo( $self ); ?>" method="post">
ID: <input type="text" name="id" size="3">
First Name: <input type="text" name="fname" size="8">
Last Name: <input type="text" name="lname" size="8"><br>
<input type="submit" value="Submit">
</form>

<?php

if( $id and $fname and $lname)
{
  $conn=@mysql_connect( "localhost", "root", "" ) or die( "Err:Conn" );

select the specified database

$rs = @mysql_select_db( "add_record", $conn) or die( "Err:Db" );

create the query

 $sql = "insert into my_table ( id, first_name, last_name ) values ( $id, \"$fname\", \"$lname\" )";

execute query

 $rs = mysql_query( $sql, $conn );

 if( $rs )
 {
   echo( "Record added:$id $fname $lname" );
 }
}

?>

</body></html> 

here am getting erro as undefined index id,fname,lastname and when i enter values in this am getting db error

user235449
  • 11
  • 5
  • You really need to read up on [SQL injection bugs](http://bobby-tables.com/) and [proper escaping](http://bobby-tables.com/php) because this is extremely dangerous code you have here. – tadman Nov 15 '13 at 05:27
  • you are using php5.3 version and in current stable version 5.5.6 mysql_* api is removed so if you are dont want to stick with 5.3 use PDO or mysqli instead http://stackoverflow.com/questions/12859942/why-shouldnt-i-use-mysql-functions-in-php/14110189#14110189 – NullPoiиteя Nov 15 '13 at 06:03

2 Answers2

4

At first when your page load $_POST['id'] value is empty because u ve'nt posted any value in $_POST[];

if(isset($_POST['submit'])){

        //all your php code here like below

        $self =  mysql_real_escape_string($_SERVER['PHP_SELF']);
        $id =    mysql_real_escape_string($_POST['id']);
        $fname = mysql_real_escape_string($_POST['fname']);
        $lname = mysql_real_escape_string($_POST['lname']);
        }

AND

$sql = "insert into my_table ( id, first_name, last_name ) values ( '$id', '$fname', '$lname' )";

By the way what is your db error??

Nabin Kunwar
  • 1,965
  • 14
  • 29
0

Those POST values will only be set when the form is POSTed. You can use isset()

$id =    isset($_POST['id'])? $_POST['id'] : NULL;

Same for others.

This happens because you have no conditions on that PHP code that will prevent it from executing the first time when the form is loaded. They should only execute when the form is submitted. You can wrap that PHP with

if(isset($_POST))
{ 
    // Your existing database code here
}
Hanky Panky
  • 46,730
  • 8
  • 72
  • 95
  • thanks for reply now changed what you said but now am getting error **Undefined variable: fname** in ` if( $id and $fname and $lname) ` – user235449 Nov 15 '13 at 05:08