从表单(Silex,postgreSQL,PHP)插入数据库


Inserting into a database from a form (Silex, postgreSQL,PHP)

我正在Heroku中制作应用程序。 我最终想制作一个用户注册页面,但我在整理语法时遇到了问题,所以现在我只想要一个列出数据库中所有名称的页面 (Postgres),有一个打开的文本框,然后单击"注册"按钮将(准备好的!)名称添加到数据库中并刷新页面,以便现在显示名称。我很难弄清楚如何做到这一点。我可以显示名称,但无法弄清楚如何从文本框中添加名称

在我的索引中.php代码:

$app->get('/db/', function() use($app) {
  $st = $app['pdo']->prepare("SELECT * FROM users  ");
  $st->execute();
  $usernames = array();
  while ($row = $st->fetch(PDO::FETCH_ASSOC)) {
    $app['monolog']->addDebug('Row ' . $row['username']);
    $usernames[] = $row;
  }
/*
{ THIS IS WHERE I WANT TO READ IN THE NEW NAME BUT I'M NOT SURE HOW
}
*/

  $st = $app['pdo']->prepare("INSERT INTO users ( username)
      VALUES ('[PUT THE NEW NAME HERE]')");
  $st->execute();

  return $app['twig']->render('database.twig', array(
    'names' => $usernames
  ));
});

$app->get('/twig/{name}', function($username) use($app) {
  return $app['twig']->render('index.twig', array(
    'username' => $username,
  ));
});

$app->run();
?>

这是我的数据库.twig文件:

从 da 中获取这些行 塔基斯:

<ul>
{% for n in names %}
  <li> {{ n.username}} at {{ n.email }}</li>
{% else %}
  <li>Nameless!</li>
{% endfor %}
</ul>
<form action="#" method="post">
 <fieldset>

<div class="form-group">
<input autofocus class="form-control" name="username" placeholder="Username" type="text"/>
</div>

<div class="form-group">
<button type="submit" class="btn btn-default">Register</button>
</div>
</fieldset>
</form>
<div>
    or <a href="login.php">log in</a> for an account
</div>
/**
  * The best option is to use HttpFoundation to catch parameters either   
  * via POST or GET. 
  * So, if you're using httpFoundation (the default behaviour with 
  * Silex) change the header like:
  */
$app->('/db/', function() use($app, Request $request){
    // rest of the code inside
});
/** for catching the new username with HttpFoundation is as easy as   
  * asking for the all or as in this case for just one field:
  */
$username = $request->request->get('username');
/**
  * Once you have the username, you can insert it into the query, but 
  * it is a nice idea to
  * bind it just to avoid sql injection, between modify
  */
$stmt = $app['db']->prepare('INSERT INTO users (?)');
$stmt->bindValue(1, $username, PDO::PARAM_INT);