我遇到麻烦,当在yii2中选择表用户时,数据没有显示
$sqlGetuser = "select * from user ";
$sqlquery = Yii::$app->db->createCommand($sqlGetuser)->query();
foreach($sqlquery as $row){
// echo $row;
// echo "saya";
echo $row['username'];
}
答案 0 :(得分:1)
错误在这一行:
$sqlquery = Yii::$app->db->createCommand($sqlGetuser)->query();
query()返回yii\db\DataReader
。要返回行数组,请使用queryAll():
$rows = Yii::$app->db->createCommand($sqlGetuser)->queryAll();
如果您想使用query()
,则需要以不同方式读取数据:
$command = $connection->createCommand('SELECT * FROM "user"');
$reader = $command->query();
while ($row = $reader->read()) {
$rows[] = $row;
}
// equivalent to:
foreach ($reader as $row) {
$rows[] = $row;
}
// equivalent to:
$rows = $reader->readAll();
在official docs中查看更多内容。
同时引用表名作为建议,因为它是保留字。