0

I'd like to insert a date to my database. Unfortunately, I didn't get it to work using a variable. If I do it manually it works like a charm.

// doesn't work
$_POST['name'] = 'Tom';
$_POST['date'] = '2020-05-05';

$sql = "INSERT INTO tbl_user (name, date) VALUES (:name, :date)";
$stmt = $pdo->prepare($sql);

foreach ($_POST as $key => $data) {
    $stmt->bindParam(':' . $key, $data);
}

// works
$_POST['name'] = 'Tom';

$sql = "INSERT INTO tbl_user (name, date) VALUES (:name, '2020-05-05')";
$stmt = $pdo->prepare($sql);

foreach ($_POST as $key => $data) {
    $stmt->bindParam(':' . $key, $data);
}

PS: I don't get any errors and at the moment I add the values manually to $_POST. $key and $data matches perfectly. If I change my database column from DATE to VARCHAR(255) it works like a charm. So it has to do with the format of the date, doesn't it?

cca
  • 69
  • 7
  • 1
    This can't be your actual code as there are multiple syntax errors here – John Conde May 17 '20 at 13:59
  • @JohnConde sorry, my mistake. I edited the code. It's just part of my actual code. – cca May 17 '20 at 14:01
  • Are you sure it is the date column giving issues? Check what `$key` and `$data` give for each iteration in the foreach loop – Rotimi May 17 '20 at 14:03
  • Can you post *all* of your actual code? I don't see anything obviously wrong with the code in the question, but it's hard to answer if you're only showing us part of it. Are you actually manually adding values into `$_POST`, or could the problem be with the form? Are you actually executing the statements? What does "doesn't work" mean - are you getting any errors, does the name insert correctly? – iainn May 17 '20 at 14:04
  • @Rotimi $key and $data shows are correct. I checked this already. – cca May 17 '20 at 14:17
  • @iainn I don't get any errors and at the moment I add the values manually to `$_POST`. `$key` and `$data` matches perfectly.. I have know idea why it doesn't work. If I change my database column from `DATE` to `VARCHAR(255)` it works like a charm. Do you have any suggestions? – cca May 17 '20 at 14:19
  • Have you configured your environment to display errors? (`error_reporting`, `display_errors`, `PDO::ERRMODE_EXCEPTION`...). In any case, it doesn't make any sense to use `bindParam()` in a loop—you destroy previous value on each iteration. Considering your SQL is static, what are you trying to do? – Álvaro González May 17 '20 at 14:50

0 Answers0