The function below is what I wrote to insert form data dynamically into db using PDO, it grabs form name and value attr to populate cols and bindValues in PDO insert statement. The problem I have now is this :
I want to hash the password before inserting and also insert time and date at the same time.
public function reg_user($data) {
if($_SERVER['REQUEST_METHOD'] == 'POST'){
$dataDB = array();
foreach ($_POST as $k => $v) {
if (in_array($k,$this->valid_keys)) {
$dataDB[$k] = $v;
}
}
$this->cols = '`'.implode('`, `', array_keys($dataDB)).'`' ;
$this->values = ':' . implode(", :", array_keys($dataDB));
$db = new db;
try{
$stmt = $db->dbh->prepare ("INSERT INTO $this->table ($this->cols ) VALUES ($this->values)");
foreach ($dataDB as $k => $v) {
$stmt -> bindValue(':'.$k, $v);
}
$stmt->execute();
} catch (PDOException $e) {
$error = new Errors();
echo "<b>".$error->displayError($e)."</b>";
}
}
}
I modified the foreach loop in to this
foreach ($_POST as $k => $v) {
if (in_array($k,$this->valid_keys)) {
if($k == 'password'){
$v = password_hash($v , PASSWORD_DEFAULT);
}
$dataDB[$k] = $v;
}
}
but I still get plain password inserted into the database.
Is this Mysql? If so there are several ways to do it without doing something code-based:
http://www.w3schools.com/sql/func_now.asp
http://www.kbedell.com/writing-projects/
In terms of hashing the password, in your loop, listen for the password's key create a special case where you set the insert value to a hashed value. You could maybe create a generic "clean" method that you pass all values too - at the very least this "clean" function would escape all insert data for malicious injection code, and it could also do any special case transformations without cluttering the insert method you show:
> foreach ($_POST as $k => $v) {
> if (in_array($k,$this->valid_keys)) {
> $dataDB[$k] = clean($k, $v);
> }
> }
clean could look something like:
function clean($key, $val){
if($key=="password")
{
$val = //hash pword here
}
return addslashes($val); //using addslashes as basic example
}
I swear, I have written code in the past that looks almost identical to yours. It is a pretty good approach. You do hit special case issue per key such as your password one, hence automating stuff like dates can be helpful.
Alternately you could use Now() when inserting each record. It is a little less elegant and doesn't really work with these ORM-ish inserts.
If not Mysql other dbs have similar approaches, postgres' example is very similar to the w3schools method.
in loop check if key is password then hash it like below
foreach ($_POST as $k => $v) {
if (in_array($k,$this->valid_keys)) {
$dataDB[$k] = ($k=="password")?md5($v):$v;
}
}
//here add the date to the array like below
$dataDB["datetime"]=date('d-m-y H:i:s');
or make the datetime column as timestamp
in your table (then it will automatically add the date and time on that row)