On the face of it, your code looks correct but also somewhat minimal - you're missing some key features I have added below:
<form action="demo.php" method="post" enctype="application/x-www-form-urlencoded" />
<p>Name: <input type="text" name="name" /></p>
<p>Comment: <input type="text" name="comment" /></p>
<input type="submit" value="submit" />
</form>
Obviously, the PHP is called demo.php, yes?
I have also changed your PHP to use MySQLi which is Improved .
The error reporting code at the top of the page is from
How do I get PHP errors to display?
<?php
/***
* First some debug output:
***/
ini_set('display_errors',1);
ini_set('display_startup_errors',1);
error_reporting(-1);
print "<pre>";
print_r($_POST);
print "</pre>";
define('DB_NAME', 'name');
define('DB_USER', 'user');
define('DB_PASSWORD', 'password');
define('DB_HOST', 'localhost');
$link = mysqli_connect(DB_HOST, DB_USER, DB_PASSWORD, DB_NAME);
if (!$link) {
die("Connection Error (" . mysqli_connect_errno() . ") ". mysqli_connect_error());
}
$name = mysqli_real_escape_string($link, $_POST['name']);
$comment = mysqli_real_escape_string($link, $_POST['comment']);
$sql = "INSERT INTO test (name, comment) VALUES ('$name', '$comment')";
mysqli_query($link, $sql) or die('Error ".__LINE__." : ' . mysqli_error($link));
To clarify some changes : You do not need MySQLi_close because the connection automatically closes at the end of the script (You also do not need to close the PHP tag, if this is the end of the file).
I have also expanded the error outputs if the MySQL connection doesn't start.
I have added real_escape_string to auto escape special characters .
At the top of the page you should see the output of $_POST
showing all values passed to the MySQL - are these populated?
I added the __LINE__
magic variable which shows the line number errors occur on. Using it in this context on a larger page is extremely useful.
Give feed back if i) this works now? and ii) if not, what notices do you get from the page?
Update:
Add value
elements to the input boxes.
<form action="demo.php" method="post" enctype="application/x-www-form-urlencoded">
<p>Name: <input type="text" name="name" value="name text"/></p>
<p>Comment: <input type="text" name="comment" value="comment text"/></p>
<input type="submit" value="submit" />
</form>
also remove the closing slash from the form element!