Skip to content

Instantly share code, notes, and snippets.

@fzaninotto
Created October 24, 2011 07:49
Show Gist options
  • Save fzaninotto/1308547 to your computer and use it in GitHub Desktop.
Save fzaninotto/1308547 to your computer and use it in GitHub Desktop.
Inserting data to a database using Faker and PDO
<?php
$pdo = new PDO('mysql:host=hostname;dbname=defaultDbName', 'username', 'p@55w0rd');
$sql = 'INSERT INTO author (first_name, last_name, date_of_birth, email) VALUES (?, ?, ?, ?)';
$stmt = $pdo->prepare($sql);
$faker = \Faker\Factory::create();
$insertedPKs = array();
for ($i=0; $i < 100; $i++) {
$stmt->bindValue(1, $faker->firstName, PDO::PARAM_STR);
$stmt->bindValue(2, $faker->lastName, PDO::PARAM_STR);
$stmt->bindValue(1, $faker->date, PDO::PARAM_STR);
$stmt->bindValue(1, $faker->email, PDO::PARAM_STR);
$stmt->execute();
$insertedPKs[]= $pdo->lastInsertId();
}
@kevinpgrant
Copy link

For anyone trying to use this - bindValues should be 1,2,3,4 (not 1,2,1,1)

add a composer.json and use composer.phar to install

{
    "require": {
        "fzaninotto/faker": "*"
    }
}

Then add the autoloader to the php

<?php
// require the Faker autoloader
require_once 'vendor/fzaninotto/faker/src/autoload.php';

DB table schema that worked...

CREATE TABLE `author` (
  `id` int(11) unsigned NOT NULL AUTO_INCREMENT,
  `first_name` varchar(255) DEFAULT NULL,
  `last_name` varchar(255) DEFAULT NULL,
  `date_of_birth` date DEFAULT NULL,
  `email` varchar(255) DEFAULT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=101 DEFAULT CHARSET=utf8mb4;

:)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment