I have the following function to insert a new row into a table:
/**
* Insert row into the designated table
*
* Function to add a new row into the designated table
*
* @param str $table Table name to insert the row
* @param arr $data Array with values
*
* @return int row Last inserted ID
*/
public function database_add_row($table, $data) {
try {
$fields = '';
foreach ($data as $field) {
$fields.= '?,';
}
$fields = substr($fields,0,-1);
$sql = "INSERT INTO ".$table." VALUES(".$fields.")";
$sth = $this->database->prepare($sql);
$sth->execute($data);
return $this->database->lastInsertId();
}
catch(PDOException $e) {
throw new userman_Exception("<h1>ups!</h1><br/>". $e->getMessage());
}
}
As to prevent sending the field names, leading to a table agnostic function, I'm counting the array of values to prepare the query, subtracting the last comma from the generated string.
Considerations:
- All columns values are passed with the
$dataarray. - The function is designed to insert on any table with any number of columns.
My question is:
Is my method adequate, leading to a secure row insertion?
