Yii2怎么执行原生sql语句查询 [ 2.0 版本 ]
$connection = Yii::$app->db;
$sql = "select * from hd_article where aid<".$aid." order by aid desc limit 1";
$command = $connection->createCommand($sql);
$res = $command->queryAll($sql);
通过这种查询,显示错误了!
共 3 个回答
-
错误呢,是PHP语法错误还是MYSQL错误
共 5 条回复Database Exception – yii\db\Exception PDOStatement::fetchAll() expects parameter 1 to be long, string given The SQL being executed was: select * from hd_article where aid<31 order by aid desc limit 1 ↵ Caused by: yii\base\ErrorException PDOStatement::fetchAll() expects parameter 1 to be long, string given in D:\WWW\web\vendor\yiisoft\yii2\db\Command.php at line 848
@yltianmei 你limit 1 就不用queryAll 用queryOne
@yltianmei 这样写是非常不安全的,有SQL注入的危险,还是建议用 连贯操作。
-
KillMeAgain 回答于 2016-04-07 16:15 举报
queryAll()
中传的不是sql语句请参考http://www.yiichina.com/doc/api/2.0/yii-db-command#queryAll()-detail
共 1 条回复 -
先创建连接对象
$connection = new \yii\db\Connection([ 'dsn' => $dsn, 'username' => $username, 'password' => $password, ]); $connection->open();
查询返回多行:
$command = $connection->createCommand('SELECT * FROM post'); $posts = $command->queryAll();
返回单行:
$command = $connection->createCommand('SELECT * FROM post WHERE id=1'); $post = $command->queryOne();
查询多行单值:
$command = $connection->createCommand('SELECT title FROM post'); $titles = $command->queryColumn();
查询标量值/计算值:
$command = $connection->createCommand('SELECT COUNT(*) FROM post'); $postCount = $command->queryScalar();
要养成先查文档的习惯:
http://www.yiichina.com/doc/guide/2.0/db-dao共 2 条回复@yltianmei 我只是把文档的内容复制过来给而已,平时要多看看文档
yltianmei
注册时间:2015-05-09
最后登录:2016-05-10
在线时长:5小时50分
最后登录:2016-05-10
在线时长:5小时50分
- 粉丝5
- 金钱142
- 威望0
- 积分192