dongxi1680 2017-03-31 16:42
浏览 36
已采纳

使用Doctrine(和Silex)将SQL数据作为数组返回

I'm using doctrine to fetch data from my MySQL database. This is all done in Silex. These are the lines of code that enable Doctrine for me.

$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');

And I'm trying to create a user class for login stuff etc. The user class looks like this:

<?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);
        }

    }
}

Though, the following is the result:

Array ( [id] => 1 [username] => araguera [password] => password [salt] => ksjdfiwe98ru2w98h )

Why does it return as an array and not as an object? Because I want to be able to do something like "$query->username".

  • 写回答

1条回答 默认 最新

  • dousuo8400 2017-03-31 17:05
    关注

    To add to u_mulder's comment, you can use PDO style to fetch results as object:

    $res = $query->fetchAll(\PDO::FETCH_OBJ);
    

    And in case you want to use fetch (to get one row) you can use:

    $res = $query->fetchObject();
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥30 深度学习,前后端连接
  • ¥15 孟德尔随机化结果不一致
  • ¥15 apm2.8飞控罗盘bad health,加速度计校准失败
  • ¥15 求解O-S方程的特征值问题给出边界层布拉休斯平行流的中性曲线
  • ¥15 谁有desed数据集呀
  • ¥20 手写数字识别运行c仿真时,程序报错错误代码sim211-100
  • ¥15 关于#hadoop#的问题
  • ¥15 (标签-Python|关键词-socket)
  • ¥15 keil里为什么main.c定义的函数在it.c调用不了
  • ¥50 切换TabTip键盘的输入法