0

I'm trying to connect my html form with MySQL database. So that what ever value the user inserts in the form our submitted to MySQL database . I have tried the following code but it is showing the following error on execution

'Undefined index: name in line 20' and 'Undefined index:address in line 21

Here is my html code

<!DOCTYPE html>
<html>
<body>
<form action="demo.php" method="post">
<p>Name: <input type="text" name="name"></p>
<p>Address: <input type="text" name="address"></p>
<input type="submit" value="Submit">
</form>
</body>
</html>

and here is my php code

<?php

define('DB_NAME', 'database');
define('DB_USER', 'root');
define('DB_PASSWORD', '');
define('DB_HOST', 'localhost:3306');

$link = mysql_connect(DB_HOST, DB_USER, DB_PASSWORD);

if (!$link) {
    die('Could not connect: ' . mysql_error());
}

$db_selected = mysql_select_db(DB_NAME, $link);

if (!$db_selected) {
    die('Can\'t use ' . DB_NAME . ': ' . mysql_error());
}

$name = $_POST['name'];
$address = $_POST['address'];

$sql = "INSERT INTO table (name, address) VALUES ('$name', '$address')";

if (!mysql_query($sql)) {
    die('Error: ' . mysql_error());
}

mysql_close();
?>
2
  • please use mysqli version and you have not check when for is submitted or not..? Commented Jul 5, 2016 at 7:02
  • try, if(isset($_POST["name"]) && isset($_POST["address"])) {...} Commented Jul 5, 2016 at 7:08

1 Answer 1

0

try this php code

  <?php

 define('DB_NAME', 'database');
 define('DB_USER', 'root');
 define('DB_PASSWORD', '');
 define('DB_HOST', 'localhost:3306');

 $link = mysql_connect(DB_HOST, DB_USER, DB_PASSWORD);

 if (!$link) {
  die('Could not connect: ' . mysql_error());
 }

 $db_selected = mysql_select_db(DB_NAME, $link);

if (!$db_selected) {
  die('Can\'t use ' . DB_NAME . ': ' . mysql_error());
}
 $name = '';
  $address = '';
 if(isset($_POST['save']))
 {
  if(isset($_POST['name'])){
   $name = $_POST['name'];
  }
   if(isset($_POST['address'])){
   $address = $_POST['address'];
  }

    $sql = "INSERT INTO table (name, address) VALUES ('$name', '$address')";

  if (!mysql_query($sql)) {
  die('Error: ' . mysql_error());
  }
  }
   mysql_close();
   ?>
Sign up to request clarification or add additional context in comments.

8 Comments

But the input provided by the user is not displayed in database
what u mean is it not inserted..?
u can see this link and use mysqli or PDO version stackoverflow.com/questions/35813617/…
the code worked but still the values were not inserted in the database
i have used the pdo version
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.