CActiveRecord::findall throws exception - yii

I'm trying to perform a search in one of my tables based on a given criteria like so:
$id = 1;
$criteria = new CDbCriteria();
$criteria->addCondition("usr_currency=:currency");
$currencies = User::model()->findAll($criteria, array(':currency' => $id,));
I get a CDbException:
CDbCommand failed to execute the SQL statement:
SQLSTATE[HY093]: Invalid parameter number: no parameters were bound.
The SQL statement executed was:
SELECT * FROM `user` `t`
WHERE usr_currency=:currency
Where as, this works:
$id = 1;
$criteria = new CDbCriteria();
$criteria->addCondition("usr_currency=:currency");
$criteria->params = array(':currency' => $id,);
$comments = User::model()->findAll($criteria);
What is wrong with the first code fragment?

From CActiveRecord::find()
This is only used when the first parameter is a string (query condition). In other cases, please use CDbCriteria::params to set parameters.

Related

How PhpStorm can recognize incomplete SQL query for check syntax and validation?

When I use full PDO query:
$db = DB::singleton();
$stmt = $db->prepare("SELECT * FROM promocode WHERE status = 1 AND code='xyz'");
$stmt->execute();
PhpStorm recognize table scheme and it suggests syntax & show wrong column name - Nice!
...but, most often I use db like this:
public function get($coupon)
{
/* table:promocode */
$db = $this->db()->retObj();
$db->where('status = 1 AND code = ?', [$coupon]);
return $db->fetch();
}
Is there any "magic" comment like (table:promocode) to tell PhpStorm that it is DB syntax?

Updating via query builder in is not working

I tried updating a column value using sql command, but it show general failure. Below is my code for update:
$name = 'ABC';
$id = 2;
$command = Yii::$app->db->createCommand()
->update('companies', ['company_name' => $name], 'company_id ='.$id.'');
$result = $command->queryAll();
When I execute this code below message is shown to me.
SQLSTATE[HY000]: General error
The SQL being executed was: UPDATE companies SET company_name='ABC' WHERE company_id =2
Error Info: Array
(
[0] => HY000
)
I cant find out why. Does anybody have any idea, what am I doing wrong here?
UPD
$command = Yii::$app->db->createCommand()
->update('companies', ['company_name' => $name], 'company_id ='.$id.'')->execute();
Can not use $command->queryAll() with update command.
There are couple of errors in your code.
First of all, why you are using queryAll() with UPDATE operation? Remove this line:
$result = $command->queryAll();
Second error - missing call of execute() command. Should be:
$command = Yii::$app->db
->createCommand()
->update('companies', ['company_name' => $name], 'company_id ='.$id.'')
->execute();
Check out documentation for yii\db\Command, especially execute() and queryAll() methods.

Issue with getting a single row in zf2 pdo

I am trying to fetch the single row using the pdo statement, but i am getting the error like ..
Fatal error: call to undefined method fetch()
$sql = new Sql( $this->adapter );
$select = $sql->select();
$select->from('users');
$where = new Where();
$where->equalTo('user_id',$userId);
$select->where($where);
//echo $select->getSqlString($this->adapter->getPlatform());
$statement = $sql->prepareStatementForSqlObject($select);
$result = $statement->execute();
$row = $statement->fetch();
//getting the result set for the below, but not the above statement fetch
$rows = array_values(iterator_to_array($result));
There's no "fetch" method in the statement object. If you want to get a single row then get the current entry of the result iterator, like so:
$row = $result->current();

PDO SQL - Update query issue

I am new to pdo and do not get why the following insert query does not work. If I remove the line that executes the query, there will be of course no insertion, but there will be no error. If I leave that line, the script is not executed. Of course I checked and rechecked the table name and field name. Hope someone can hep me understand. Note that before executing the query, the ber_mBacth_date field of my table is set to NULL. Cheers. Marc
<?php
$db_host = 'localhost';
$db_user = 'user';
$db_password = 'user';
$db_database = 'myconsole';
$mBatchDate = date('Y-m-d H:i:s');
$connexion = new PDO("mysql:host=$db_host;dbname=$db_database", $db_user, $db_password);
$qry = $connexion->execute('UPDATE batcherrors SET ber_mBatch_date = "'.$mBatchDate.'"');
$connexion = NULL;
?>
Can you try instead of:
$connexion = new PDO("mysql:host=$db_host;dbname=$db_database", $db_user, $db_password);
$qry = $connexion->execute('UPDATE batcherrors SET ber_mBatch_date = "'.$mBatchDate.'"');
do:
$statement = $connexion->prepare("UPDATE batcherrors SET ber_mBatch_date = :mBatchDate");
$statement->bindValue(':mBatchDate', $mBatchDate, PDO::PARAM_STR);
$statement->execute();
Binding is recommended way to set parameters values (over concatenation).

Parameterized LIKE clause in SQL statement using Dapper

I want to perform the following query using Dapper, which currently doesn't return expected results (I think it must be treating the #pName param as literal text within the single quotes?):
var q = "SELECT * FROM Users WHERE Name LIKE '#pName%'";
#pName is the param I assign a value to upon executing the query.
Things work if I just build the SQL like:
var q = "SELECT * FROM Users WHERE Name LIKE '" + name + "%'";
.. but I would prefer to use a param if possible.
I am executing the query using the following code:
o = _cn.Query<User>(q, new { pName = new DbString { Value = name, IsFixedLength = false, Length = 25, IsAnsi = true } }).ToList();
How do I got about this using Dapper?
SELECT * FROM Users WHERE Name LIKE #pName + '%'
I would like to add here another possible solution:
var results = cn.Query("SELECT * FROM Table WHERE Column LIKE #value", new { value = value + "%" });
The wildcard is inside the string var itself, and then we reference that var in the SQL. Applies to any wildcard pattern you want.