dagitab
dagitab

Reputation: 133

Silex cannot insert to database

I am working on a simple silex api. I would just like to use mysql as db, but as I went on to put simple insert statements using silex, it doesn't seem to continue.

Here is my index.php:

<?php
require_once __DIR__.'/../vendor/autoload.php';
$app = new Silex\Application();
$app['debug'] = true;

//database connection settings
$app->register(new Silex\Provider\DoctrineServiceProvider(), array(
    'db.options' => array(
        'dbname' => 'silexdb',
        'user'   => 'root',
        'host'     => 'localhost',
        'driver'   => 'pdo_mysql',
        'port'     => 3306
    ),
));

$app['db']->insert('users', array(
        'firstName' => 'Gabriel',
        'lastName' => 'Gagno'
    )
);

//routes
$app->get('/hello', 'App\\Controllers\\HelloController::hello');

$app->run();

?>

And my composer.json:

{
    "require": {
      "silex/silex": "~1.3",
      "symfony/browser-kit": "~2.3",
      "symfony/console": "~2.3",
      "symfony/config": "~2.3",
      "symfony/css-selector": "~2.3",
      "symfony/dom-crawler": "~2.3",
      "symfony/filesystem": "~2.3",
      "symfony/finder": "~2.3",
      "symfony/form": "~2.3",
      "symfony/locale": "~2.3",
      "symfony/process": "~2.3",
      "symfony/security": "~2.3",
      "symfony/serializer": "~2.3",
      "symfony/translation": "~2.3",
      "symfony/validator": "~2.3",
      "symfony/monolog-bridge": "~2.3",
      "symfony/twig-bridge": "~2.3",
      "doctrine/dbal": "~2.2",
      "swiftmailer/swiftmailer": "5.*"
    },
    "autoload" : {
      "psr-4" : {
        "App\\Controllers\\" : "app/controllers"
      }
    }
}

what am I doing wrong? thanks!

Upvotes: 2

Views: 2073

Answers (1)

Meathanjay
Meathanjay

Reputation: 2073

Put insert code within a route function:

$app->get('/insert',function() use $app {

    $app['db']->insert('users', array(
        'firstName' => 'Gabriel',
        'lastName' => 'Gagno'
      )
    );

});

Now access /insert to execute to insert code.

Upvotes: 4

Related Questions