0

What is the best way to insert a PHP 5 form into a MySQL database?

<form  action="script.php" method="post">
 <fieldset>
  <input id="name" type="text" placeholder="name" />
  <input type="submit" value="Opslaan" />           
 </fieldset>
</form>​    

Do I still have you use all of these?

$name= $_POST['name'];  
$name = stripslashes($name);  
$name = mysql_real_escape_string($name);

mysql_connect($host,$username,$password);
@mysql_select_db($database) or die( "Unable to select database");
$query = "INSERT INTO names VALUES ('','$name')";
mysql_query($query);
mysql_close();

Because when I do this, the script only enters the ID, the name field remains empty..

EDIT: How to use PDO or mysqli in PHP 5 (by the latest standards)?

atMaarten
  • 93
  • 3
  • 12
  • First do not use mysql_* as it is deprecated on PHP 5.5. You asked for the best way, use PDO or MySQLi with prepared statements. – Prix Aug 30 '13 at 22:41

2 Answers2

2

You need your name input to have the name attribute="name" ie.

<input type="text" id="name" name="name" placeholder="Enter your name" />

To fully address your answer.

  • The mysql_* library is deprecated on the latest PHP's and SHOULD NOT be used. Use PDO or MySQLi instead. Thanks to Prix for pointing that out.
  • You'll want to sanitize data that users give. This question has been asked before and a good answer exists here: What's the best method for sanitizing user input with PHP?
  • The reason your _POST parameter was not doing anything on your name input was due to the fact that was mentioned above.
Community
  • 1
  • 1
aztechy
  • 640
  • 7
  • 15
  • 1
    See also: [Difference between id and name attributes in HTML](http://stackoverflow.com/q/1397592/2359271) – Air Aug 30 '13 at 22:32
  • 1
    Nothing about mysqli or pdo? – Davit Aug 30 '13 at 22:35
  • Great that worked out well! Are the stripslashes($name) and mysql_real_escape_string($name) operations still needed in PHP 5? – atMaarten Aug 30 '13 at 22:36
  • The practice of sanitizing the data that your end-users put in is a good thing. Those are valid methods to use, however, with regards to mysql_real_escape_string that function will be deprecated. Read this for further information: http://php.net/manual/en/function.mysql-real-escape-string.php. – aztechy Aug 30 '13 at 22:42
0

The placeholder attribut allows in html 5 to put a default value in an element of a form. This default value is remove when the element has focus. But in your case you have forget the attribut name. Try this:

<form  action="script.php" method="post">
 <fieldset>
  <input id="name" name="name" type="text" placeholder="Enter your name" />
  <input type="submit" value="Opslaan" />           
 </fieldset>
</form>​
Raspoutine
  • 82
  • 1
  • 7