Hi there,
I am trying to insert a row/record into my table using PDO. I have a form that accepts user input. Here’s a piece of the code I have written:
[php] foreach ($_POST as $column => $data) {
if (!isset($_POST[$column]) || empty($_POST[$column])) {
echo ‘Fill out all fields!’;
exit;
}
$tableFields[$column] = trim($data);
}
$date = new DateTime();
$tableFields['date_added'] = $date->format('Y-m-d H:i:s');
$tableFields['added_by'] = 'Vince';
$tableFields['notes'] = date('M d, Y') . ' - ' . $tableFields['notes'] . ' - ' . $tableFields['added_by'];
unset($tableFields['savetemplate']);
// DB Info hidden
$db = new PDO("mysql:host=$dbhost; dbname=$dbname", $dbuser, $dbpass);
// DB fields/structure: id, title, template, notes, active, date_added, date_updated, added_by, edited_by
$fields = implode(', ', array_keys($tableFields));
$param = NULL;
foreach ($tableFields as $paramKey => $paramValue) {
$param .= ':' . $paramKey . ', ';
}
$param = rtrim($param, ', ');
$query = 'INSERT INTO `mytable` (' . $fields . ') VALUES (' . $param . ')';
$stmt = $db->prepare($query);
var_dump($tableFields);
/* Running a var_dump($tableFields) at this point in the script yields the following results:
array (size=6)
'title' => string 'Testing title' (length=9)
'template' => string 'Testing template' (length=9)
'notes' => string 'Jun 19, 2014 - Test - Vince' (length=32)
'active' => string 'Y' (length=1)
'date_added' => string '2014-06-19 03:10:07' (length=19)
'added_by' => string 'Vince' (length=3)
*/
foreach ($tableFields as $key => $value) {
$stmt->bindParam(":$key", $value);
}
$stmt->execute();
$db = NULL;[/php]
Seems like the last parameter bound is $tableFields[‘added_by’], which holds the value ‘Vince’. Since it is the last parameter that’s being bound by the foreach() loop, the value of that last key, which is ‘Vince’, seems to be inserted into all non-numeric fields in my table. What I should be seeing in my table are the results from var_dump($tableFields) as provided in the code above. I have also provided a brief list of the columns in my database table.
All help is appreciated. Thank you very much!