0

I'm completely stumped with this one.

I'm using PDO to insert a record into a generic 'users' table and when attempting to insert one record, two identical records are being inserted. It's as if the insert statement is running twice. As an added note, this code is being run on a vagrant machine (scotchbox/pro). The vagrant machine is serving correctly and the code shown below is the first thing in my index file, so no other code is affecting it.

index.php:

<?php

$host = 'localhost';
$user = 'root';
$password = 'root';
$dbname = 'home';

$dsn = 'mysql:host=' . $host . ';dbname=' . $dbname;

$pdo = new PDO($dsn, $user, $password);
$pdo->setAttribute(PDO::ATTR_DEFAULT_FETCH_MODE, PDO::FETCH_OBJ);

$admin = 0;
$name = 'Frank';

$sql = 'INSERT INTO users(name, admin) VALUES (:name, :admin)';

$statement = $pdo->prepare($sql);
$statement->execute(['name' => $name, 'admin' => $admin]);

die();

.htaccess:

<IfModule mod_rewrite.c>
  Options -Multiviews
  RewriteEngine On
  RewriteBase /
  RewriteCond %{REQUEST_FILENAME} !-d
  RewriteCond %{REQUEST_FILENAME} !-f
  RewriteRule  ^(.+)$ index.php?url=$1 [QSA,L]
</IfModule>

I've tried removing specific lines that could be affecting it such as the setAttribute line but to no avail. Any help would be amazing! Thanks in advance.

Jay Blanchard
  • 34,243
  • 16
  • 77
  • 119
Joe
  • 13
  • 4
  • 3
    if you run JUST the above ( obviously with correct db info ) does the double insert occur? – Professor Abronsius Mar 03 '20 at 19:03
  • 1
    Your code looks OK as far as I can tell - I can't see any reason why it would run twice. Is it possible that this file is being included more than once? – CountKyle Mar 03 '20 at 19:07
  • 1
    If you're running this from a browser, check the network tab of developer tools to check there definitely aren't any unexpected requests being sent. – iainn Mar 03 '20 at 19:09
  • Edit this line: `$statement->execute(['name' => $name, 'admin' => $admin]);` to look like this: `$statement->execute([':name' => $name, ':admin' => $admin]);` – Serghei Leonenco Mar 03 '20 at 19:20
  • It turns out that my .htaccess file was the offending code although I don't quite understand why... Upon removing the .htaccess file, it inserted correctly. Upon re-adding the file (with no code changes, essentially back to when the error was occuring) the issue is still gone! I'm going to add my public/.htaccess code to the original post for anyone interested. – Joe Mar 03 '20 at 19:23
  • 2
    @SergheiLeonenco colons are not needed in array keys. – miken32 Mar 03 '20 at 20:15

0 Answers0