I am new to mysql php and I have been struggling to make this simple name entry form work but it has been failing on me by inserting blank entries. I have been looking arround the web for a while but nothing has been helpful.
This is my html form
<form action="demo.php" method="post">
name:<input type="text" name="input1">
<br/>
<input type="submit" value="submit">
</form>
My php code
<?php
define('db_name', 'demo');
define('db_user', 'root');
define('db_password', 'password');
define('db_host', 'localhost');
$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());
}
$value = $_post['input1'];
$sql = "insert into demo (name) values ('$value')";
if (!mysql_query($sql)) {
die('Error: ' . mysql_error());
}
mysql_close();
?>
Mysql table
+-------+-------------+------+-----+---------+----------------+
| Field | Type | Null | Key | Default | Extra |
+-------+-------------+------+-----+---------+----------------+
| id | int(11) | NO | PRI | NULL | auto_increment |
| name | varchar(30) | YES | | NULL | |
+-------+-------------+------+-----+---------+----------------+
I'm surprised you didn't see the big red-ish (pink?) warning on all the mysql_*
functions in the PHP manual. To summarise...
Warning This extension is deprecated as of PHP 5.5.0, and will be removed in the future. Instead, the MySQLi or PDO_MySQL extension should be used.
So, on that advice, I suggest you try mysqli.
In regards to your specific problem, I'd say it's as Fred said in the comments, $_post
should be $_POST
. In PHP, variable names are case sensitive.
You should also prepare an INSERT statement and use parameter binding to avoid SQL injection vulnerabilities.
Here's an example to summarise...
$link = new mysqli('localhost', 'root', 'password', 'demo');
if ($link->connect_errno) {
throw new Exception($link->connect_error, $link->connect_errno);
}
// Check that the expected value has been provided via a POST request
if (!isset($_POST['input1'])) {
throw new Exception('Missing POST request parameter [input1]');
}
// now prepare an INSERT statement
if (!$stmt = $link->prepare('INSERT INTO `demo` (`name`) VALUES (?)')) {
throw new Exception($link->error, $link->errno);
}
// bind parameters
$stmt->bind_param('s', $_POST['input1']);
if (!$stmt->execute()) {
throw new Exception($stmt->error, $stmt->errno);
}
Try this:
First Check value of text input & then use it in the query.
$value = $_POST['input1'];
echo $value; exit;
check $value
. Do you get value you entered in textbox ??
If Yes then use it in the Query.
- Thanks
also you can use: $value = filter_input(INPUT_POST, 'var_name')
, and of course you should start using PDO.