I have this form and process page.
On a form page, there are two hidden inputs id and reg_time values set to null at the "end " when executing no problem with id but under the row reg_time I get 0000-00-00 00:00:00 timestamp set in table users. Any suggestions why?
function post($POST)
{
$POST = array_map('trim', $_POST);
$hash = "$2y$10$";
$salt = "nekiludistringzahash22";
$his = $hash . $salt;
$POST['pass'] = crypt($_POST['pass'],$his);
return $POST;
}
$sql = "insert into users values(:" . implode(",:", array_keys(post($_POST))) . ");";
try{
$db = new PDO('mysql:host=localhost;charset=utf8;dbname=dbname','root','');
$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
}catch (PDOException $e)
{
die("Conn problem " . $e->getMessage());
}
$reg = $db->prepare($sql);
$reg->execute(post($_POST));
and form
<form action="exp2.php" method="post">
<input type="hidden" name="id" value="null">
<input type="text"name="uname">
<input type="text"name="pass">
<input type="text"name="name">
<input type="text"name="lname">
<input type="submit">
<input type="hidden" name="reg_time" value = "null">
</form>
Your problem is quite common.
Many learners cannot tell a NULL
value from a string that consists of four letters "NULL". While the latter has absolutely no special meaning.
And also there are bad news: HTTP protocol is text-based. Means one cannot send anything but a string using an HTTP method, and thus a NULL
value cannot be sent over HTTP POST.
To make this code work, you have to add your NULLs at the server side, just like you are doing it for the password:
function post($POST)
{
$POST = array_map('trim', $_POST);
$hash = "$2y$10$";
$salt = "nekiludistringzahash22";
$his = $hash . $salt;
$POST['pass'] = crypt($_POST['pass'],$his);
$POST['reg_time'] = NULL;
$POST['id'] = NULL;
return $POST;
}
However, it is not the main problem with your code. The worst news is that your code is severely vulnerable to sql injection, despite the seemingly proper binding.
To make it safe, make your function accept the list of allowed fields, and assign a NULL
value to absent ones:
function post($allowed)
{
$post = array();
foreach ($allowed as $key)
{
if (isset($_POST[$key])) $post[$key] = trim($_POST[$key]);
else $_POST[$key] = NULL;
}
$hash = "$2y$10$";
$salt = "nekiludistringzahash22";
$his = $hash . $salt;
$POST['pass'] = crypt($_POST['pass'],$his);
}
And then call it like this:
$post = post(array('id','uname','pass','name','lname','reg_time'));
$sql = "insert into users values(:" . implode(",:", array_keys($post)).");";
$reg = $db->prepare($sql);
$reg->execute($post);
this way you will have all the field names filtered out.
As a bonus, you'll be able to assign a custom value to your submit button ;)