How to use IN/AND clause in Yii framework? - mysql-error-1064

I have a MySQL table with 3 columns: ID, name, user.
I wish to use the following SQL with Yii framework:
$sql = "SELECT * FROM my_table WHERE idName=".$name." AND user IN .$arrayOfUsers;
// $arrayOfUsers is an array of int [0]->1, etc.
I tried in three different ways, but without success:
1)
$sql = "SELECT * FROM my_table WHERE idName=".$name." AND user IN .$arrayOfUsers;
$command = $connection->createCommand($sql);
$dataReader = $command->query();
$query = $dataReader->readAll();
The error is:
PHP Error [8]
Array to string conversion
2)
$query = Yii::app()->db->createCommand()
->select('*')
->from('my_table')
->where(array('and', array('in', 'user', $arrayOfUsers), array('idName' => $name)))
->queryAll();
The error is:
PHP Error [8]
Undefined offset: 0
3)
$query = Yii::app()->db->createCommand()
->select('*')
->from('my_table')
->where(array('and', array('in', 'user', $arrayOfUsers), 'idName='.$name)))
->queryAll();
The error is:
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 'idName=7)'
at line 3. The SQL statement executed was: SELECT * FROM
my_table WHERE (user IN ('1', '2', '3', '4')) AND
(idName=7)

There has many ways to do but I'd like to use Active Record to handle this thing.
However, your question was around Query Builder, I give you correct one
Edited: (As your comment, idName is big INT instead of var char)
1) You got error because you pass $arrayOfUsers which was array, not expected string on your sql. It should be
$connection=Yii::app()->db;
$sql = "SELECT * FROM my_table WHERE idName=".$name." AND (user IN(".implode(',',$arrayOfUsers)."))";
$command = $connection->createCommand($sql);
$query = $command->queryAll();
2) Using Query builder and where operator
$query = Yii::app()->db->createCommand()
->select('*')
->from('my_table')
->where(array('in', 'user', $arrayOfUsers))
->andwhere('name = :name', array('idName'=>$name))
->queryAll();
3) If you want to wrap them together, it'll be fine, but they look unsightly like this
$query = Yii::app()->db->createCommand()
->select('*')
->from('my_table')
->where(array('and', 'idName= ' . $name, array('in', 'user', $arrayOfUsers)))
->queryAll();
More references how to use where operator from official document
// WHERE id=1 or id=2
where('id=1 or id=2')
// WHERE id=:id1 or id=:id2
where('id=:id1 or id=:id2', array(':id1'=>1, ':id2'=>2))
// WHERE id=1 OR id=2
where(array('or', 'id=1', 'id=2'))
// WHERE id=1 AND (type=2 OR type=3)
where(array('and', 'id=1', array('or', 'type=2', 'type=3')))
// WHERE `id` IN (1, 2)
where(array('in', 'id', array(1, 2))
// WHERE `id` NOT IN (1, 2)
where(array('not in', 'id', array(1,2)))
// WHERE `name` LIKE '%Qiang%'
where(array('like', 'name', '%Qiang%'))
// WHERE `name` LIKE '%Qiang' AND `name` LIKE '%Xue'
where(array('like', 'name', array('%Qiang', '%Xue')))
// WHERE `name` LIKE '%Qiang' OR `name` LIKE '%Xue'
where(array('or like', 'name', array('%Qiang', '%Xue')))
// WHERE `name` NOT LIKE '%Qiang%'
where(array('not like', 'name', '%Qiang%'))
// WHERE `name` NOT LIKE '%Qiang%' OR `name` NOT LIKE '%Xue%'
where(array('or not like', 'name', array('%Qiang%', '%Xue%')))
http://www.yiiframework.com/doc/guide/1.1/en/database.query-builder

Try this
$criteria = new CDbCriteria();
$criteria->select = "*";
$criteria->condition = "idname = :name ";
$criteria->params = array (
':name' => $name,
);
$criteria->addInCondition('user', $arrayOfUsers);
my_table::model()->findAll($criteria);

Related

magento 2 collection gives empty data?

below is my code:
$transObj = $this->_objectManager->create('Magento\Sales\Model\Order\Payment\Transaction');
$order_id = 9706;
$trans_result = $transObj->getCollection()
->addAttributeToSelect(
'order_id'
)
->addAttributeToSelect(
'payment_id'
)
->addAttributeToSelect(
'is_closed'
)
->addAttributeToSelect(
'txn_id'
)
->addAttributeToSelect(
'transaction_id'
)
->addFieldToFilter(
'order_id',
array("eq" => $order_id)
);
var_dump($trans_result->getData());
echo "\n Query:".$trans_result->getSelect();
below i am getting the out put as :
array(0) {
}
Query :SELECT main_table.order_id, main_table.payment_id, main_table.is_closed, main_table.txn_id, main_table.transaction_id FROM sales_payment_transaction AS main_table WHERE (order_id = 9706)
when i run the query in the Mysql , i am getting the data fetched properly.
But when i check the output of the result ($trans_result) using getData();
i am getting empty data.
Any help will be appreciated.?
Thanks in advance.
I'm pretty sure its within the attributes. Make it simpler.
$order_id = 9706;
$trans_result = $transObj->getCollection()
->addFieldToFilter('order_id', array('eq' => $order_id))
You should the same value because you're using all columns from the table, so there's no necesity to addfielters on SELECT clause. Although if you want to Select an scpecific column use
$trans_result = $trans_result->addFieldToSelect('payment_id')
Note I'm using addFieldToSelect instead of addAttributeToSelect

Active records class in CodeIgniter

Basicly i have two tables photos and users. I wanna join tables and Update colums image_max and image_min. I get error unknown colum username. In which way i can join two tabels and get data from both. My sintax is:
$this->db->select('*');
$this->db->from('photos');
$this->db->join('users', 'photos.id = users.id');
$this->db->where('username',$username);
$this->db->update('photos',$data);
And I get error
Unknown column username in where clause
UPDATE `photos` SET `image_max` = '', `image_min` = '' WHERE `username` = 'wwww'
apparently you need a letter on the table should say "users.username", check that.
Greetings.
$this->db->select('*');
$this->db->from('photos');
$this->db->join('users', 'photos.id = users.id');
$this->db->where('users.username',$username);
$this->db->update('photos',$data);
You don't need to use "select and from" before upload fields, just update in this way
$data = array('image_max'=> 4, 'image_min' => 1);
$this->db->join('users', 'photos.id = users.id');
$this->db->where('username',$username);
$this->db->update('photos',$data);

Can't add additional where queries in Ardent Model

I'm having a problem using LaravelBook/Ardent. My logic is exclude the soft deleted rows in unique validation using the code:
public static $rules = array(
'name' => 'required|unique:paper_colors,name,deleted_at,NULL',
'description' => 'required|between:2,255',
'code' => 'required'
);
But when I run the updateUniques I'm still getting The name has already been taken. and this sql:
select count(*) as aggregate from `paper_colors` where `name` = '4/0' and `id` <> '2'
I'm expecting the sql will be:
select count(*) as aggregate from `paper_colors` where `name` = '4/0' and `id` <> '2' and `deleted_at` is null
Can someone help me to solve this. I'm stuck almost last night on this. Still can't figure it out how to deal with this.
I found out that Ardent is dropping the Laravel Validation feature: Adding Additional Where Clauses
So my solution to overcome this bug is to add additional code under LaravelBook\Ardent\Ardent#buildUniqueExclusionRules at line: 799, but I didn't do that since I'm depending for their any updates in the future. So I just create a class that extend LaravelBook\Ardent\Ardent and copy buildUniqueExclusionRules and modify it.
if (count($params)>2)
{
$c = count($uniqueRules);
for ($i=1; $i < count($params); $i++, $c++) {
$uniqueRules = array_add($uniqueRules, $c, $params[$i]);
}
}

jdatabase no numbers appearing in article

I am testing outputting a query in a article in Joomla 3.0.2 via Sorcerer.
When i output the array storing the query only values that are no numbers are appearing.
E.g. say i have 2 rows in a table called 'goofy' like this
id, description
1, test
2, test2
My code then looks like this
$query = "SELECT * FROM goofy";
$db->setQuery($query);
$results = $db->loadAssocList();
print_r($results);
The output I am getting in the article is like this;
Array ( [0] => Array ( [id] => [description] => test ) [1] => Array ( [id] => [description] => test2 ) )
Any ideas why the numbers wont output?
$db = JFactory::getDBO();
$query = $db->getQuery(true);
$query->select('*');
$query->from('goofy');
$db->setQuery($query);
$results = $db->loadAssocList();
print_r($results);
You haven't specified the table name correctly. When using database queries, you have to add the prefix onto the table name. You also need to call the database using $db = JFactory::getDBO();
So your query should be like this:
$db = JFactory::getDBO();
$query = "SELECT * FROM #__goofy";
$db->setQuery($query);
$results = $db->loadAssocList();
print_r($results);
If you database table isn't Joomla related, then you don't need to use the #__ prefix.

CodeIgniter is discarding JOIN clause in SQL statement (Active Record)

I have the following function in one of my CI models:
function update_uu_feature($feature, $lang, $data)
{
$feature = str_replace('_', '-', $feature);
$this->db->where('navigation', $feature);
$this->db->where('language', $lang);
$this->db->join('all_video_names', 'all_video_names.video_id = all_uu_features.video_id', 'inner');
return $this->db->update('all_uu_features', $data);
}
But the “join” line gets discarded. In the profiler, it outputs:
UPDATE `all_uu_features` SET `page_title` = 'Laser', `title` = 'Test', `keywords` = 'Test', `description` = 'Test', `feature_text` = '<p>Test text</p>', `learn_more_about` = 'Test Text 2', `overview` = 'test', `copy` = 'test' WHERE `navigation` = 'laser-interface' AND `language` = 'en'
Can someone help me with the syntax? Thanks. Most of the data is in the all_uu_features table, except for the video name, which is in the all_video_names table. The two are joined on the video_id column in each table. In other words, all of the columns in the above statement are in all_uu_features except for video name. Hope that's clear.
The SQL statement above shows the data is being returned in the post and being processed by the function, it's just not accepting the join for some reason.
It looks to me very much like CI's Active Record class doesn't support using joins in its update() operation. Certainly if you have a look at the code (in DB_active_rec.php), the update() method doesn't even look at any joins that have been set up
From update():
$sql = $this->_update($this->_protect_identifiers($table, TRUE, NULL, FALSE), $this->ar_set, $this->ar_where, $this->ar_orderby, $this->ar_limit);

Resources