SQL 使用 Doctrine(和 Silex)将数据作为数组返回
SQL data is returned as an array using Doctrine (and Silex)
我正在使用 doctrine 从我的 MySQL 数据库中获取数据。这一切都在 Silex 中完成。这些是为我启用 Doctrine 的代码行。
$config = new \Doctrine\DBAL\Configuration();
$connParams = array(
'driver' => 'pdo_mysql',
'dbname' => 'webshop',
'host' => 'localhost',
'user' => 'root',
'password' => '',
'charset' => 'utf8'
);
$conn = \Doctrine\DBAL\DriverManager::getConnection($connParams, $config);
$app['dbcon'] = $conn;
$app->get('/', function () use ($app){
$user = new User($app['dbcon']);
return $app['twig']->render('home.twig', [
'content' => 'Home',
]);
})->bind('home');
我正在尝试创建一个用户 class 用于登录等。用户 class 如下所示:
<?php
namespace Models;
class User
{
private $db;
public function __construct($db)
{
$this->db = $db;
$query = $this->db->prepare("SELECT * FROM users");
$query->execute();
$query = $query->fetchAll();
foreach($query as $user){
print_r($user);
}
}
}
不过,结果如下:
Array ( [id] => 1 [username] => araguera [password] => password [salt] => ksjdfiwe98ru2w98h )
为什么它 return 作为数组而不是对象?因为我希望能够执行类似“$query->username”的操作。
要添加到 u_mulder 的评论中,您可以使用 PDO
样式将结果作为对象获取:
$res = $query->fetchAll(\PDO::FETCH_OBJ);
如果您想使用 fetch
(获得一行),您可以使用:
$res = $query->fetchObject();
我正在使用 doctrine 从我的 MySQL 数据库中获取数据。这一切都在 Silex 中完成。这些是为我启用 Doctrine 的代码行。
$config = new \Doctrine\DBAL\Configuration();
$connParams = array(
'driver' => 'pdo_mysql',
'dbname' => 'webshop',
'host' => 'localhost',
'user' => 'root',
'password' => '',
'charset' => 'utf8'
);
$conn = \Doctrine\DBAL\DriverManager::getConnection($connParams, $config);
$app['dbcon'] = $conn;
$app->get('/', function () use ($app){
$user = new User($app['dbcon']);
return $app['twig']->render('home.twig', [
'content' => 'Home',
]);
})->bind('home');
我正在尝试创建一个用户 class 用于登录等。用户 class 如下所示:
<?php
namespace Models;
class User
{
private $db;
public function __construct($db)
{
$this->db = $db;
$query = $this->db->prepare("SELECT * FROM users");
$query->execute();
$query = $query->fetchAll();
foreach($query as $user){
print_r($user);
}
}
}
不过,结果如下:
Array ( [id] => 1 [username] => araguera [password] => password [salt] => ksjdfiwe98ru2w98h )
为什么它 return 作为数组而不是对象?因为我希望能够执行类似“$query->username”的操作。
要添加到 u_mulder 的评论中,您可以使用 PDO
样式将结果作为对象获取:
$res = $query->fetchAll(\PDO::FETCH_OBJ);
如果您想使用 fetch
(获得一行),您可以使用:
$res = $query->fetchObject();