I have this sql query
SELECT * FROM form_fields
WHERE id NOT IN ("3", "1", "6")
ORDER BY FIELD (id, "3" ,"1" ,"6")
which i want to convert to an yii1 query. So i tried like this
$SQL="SELECT * FROM form_fields WHERE id NOT IN {$sorted_array} ORDER BY FIELD (id, $sorted_array)";
$connection=Yii::app()->db;
$command=$connection->createCommand($SQL);
$rowCount=$command->execute();
$dataReader=$command->query();
where $sorted_array has value Array ( [0] => 3 [1] => 1 [2] => 6 )
It gave me an error
PHP notice
Array to string conversion
then i converted the $sorted_array to string like this
$string = implode(' ', $sorted_array);
and again executed the query
$SQL="SELECT * FROM form_fields WHERE id NOT IN {$string} ORDER BY FIELD (id, $string)";
$connection=Yii::app()->db;
$command=$connection->createCommand($SQL);
$rowCount=$command->execute();
$dataReader=$command->query();
Now i get another error
CDbException
CDbCommand failed to execute the SQL statement: SQLSTATE[42000]: Syntax error or access violation: 1064 You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '3 1 6 ORDER BY FIELD (id, 3 1 6)' at line 1. The SQL statement executed was: SELECT * FROM form_fields WHERE id NOT IN 3 1 6 ORDER BY FIELD (id, 3 1 6)
Instead of this
SELECT * FROM form_fields
WHERE id NOT IN ("3", "1", "6")
ORDER BY FIELD (id, "3" ,"1" ,"6")
my yii1
query produced this erroneous sql query
SELECT * FROM form_fields
WHERE id NOT IN 3 1 6 ORDER BY FIELD (id, 3 1 6)
Any help would be appreciated
implode的第一个参数应该是逗号:
$string = implode(',', $sorted_array);
The better way is use QueryBuilder. It looks like
$result = Yii::app()->db->createCommand()
->select('field1, field2')
->from('table t')
->join('table2 t2', 't2.t_id = t.id')
->where('t.property = :property', [':property' => 1])
->queryRow();
It's more useful, because QueryBuilder use PDO-statements for parameters, and makes correct queries in SQL dialect which depends of your DBMS type.
It also supports array statements, like this:
->where(['in', 'field', [1,2,3]])
The result is:
... WHERE field IN (1, 2, 3) ...
And yes, it's still DAO, without ActiveRecord :)
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.