在Symfony中访问数据库连接数据


Access the database connection data, in Symfony

我在Symfony有点新,我有这个问题。我想访问数据库连接数据,在app/config/参数。这是一个php文件,位于src/Myproject/MyBundle/Resources/public/query.php。这只是为了运行一个查询。如果我运行这段代码,它可以工作,但我想要更安全的。

$link = mysql_connect('localhost', 'root', '');
if (!$link) {
   die('Not connected : ' . mysql_error());
}
$db_selected = mysql_select_db('database2', $link);
if (!$db_selected) {
   die ('Can''t use foo : ' . mysql_error());
}

你所需要的是在你的控制器中为你的Ajax url创建一个路由和适当的动作那么你就不需要在Resources文件夹

中创建php文件了

1)为Ajax生成路由

mybundle_ajaxrequest:
   pattern: /ajaxcheck
   defaults: { _controller: myBundle:Default:ajaxCheck }
2)在默认控制器中创建适当的动作,并将所有后端代码放入 中
public function ajaxCheckAction() {
   $host_name = $this->container->getParameter('database_host');
   // do any logic you need here
   $response = new Response();
   $response->header->set('Content-Type', 'application/json');
   $response->setContent(json_encode(array('host' => $host_name))); //return whatever you need
   return $response;
}
在你的jQuery请求中,你需要将url设置为生成的路由
$(document).ready(function(){ 
   // ajax setup 
   $.ajaxSetup({ 
      url: '{{ path('mybundle_ajaxrequest') }}', 
      type: 'POST', 
      cache: 'false' 
   });
});
现在你就可以在jQuery ajax中处理返回的json响应了
请记住你的jQuery应该在一个模板文件(twig模板文件)