jdatabase no numbers appearing in article - joomla

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.

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

result_array() data in where clause in OR condition : Active records Codeigniter

result_array() for a query gives the following :
Array ( [0] => Array ( [id] => 1 ) [1] => Array ( [id] => 4 ) )
I want to use id=1 and id=4 in the where clause in the OR condition like the following :
$this->db->where_in('id',$query->result_array());
But the above causes error. Is there any direct way of doing the same?
You can simply use array_column
array_column($query->result_array(), 'id')
here is reference to it.
$result = $roleIdQuery->result_array();
$column = array_map(function($sub)
{
return $sub['id'];
}, $result);
I used this. Sadly.
because it has arrays within that array.
$ids=array();
$resultArray=$query->result_array();
foreach($resultArray as $result){
$ids[]=$result['id'];
}
$ids // this is what you need to pass now..
If you change your original query to use GROUP_CONCAT. Not an option in Active Record so would need to write your own SQL. something like
$query= $this->db->query('SELECT GROUP_CONCACT(id) AS ids FROM table WHERE condition=true');
Then you should be able to do
$this->db->where_in('id',$query->result_array()[0]['ids']);
Just noticed your on 5.3 so unfortunately that means this won't work you will have to do.
$result = $query->result_array();
Then pass in $result[0]['ids']

Active record of not in

$this->db->query('DELETE FROM default_model WHERE cat_id NOT IN (SELECT id FROM default_category)');
the active record format for this query
$query = $this->db->select('id')
->get('category')->result();
$this->db->where_not_in('cat_id',$query )
->delete('model');
I tried a lot but could not do it. How to pass $query
The query results are returned as standard objects. Therefore you need to fetch the ids from the returned objects in a non associative array before passing that array to the delete query.
Like this:
$result = $this->db->select('id')->get('category')->result();
$ids = [];
foreach($result as $result)
$ids[] = $result->id;
$this->db->where_not_in('cat_id', $ids)->delete('model');

How to use IN/AND clause in Yii framework?

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);

Insert multiple rows using a single query

Can Joomla's DB object add multiple rows at once? MySQL can do this like so:
INSERT INTO x (a,b)
VALUES
('1', 'one'),
('2', 'two'),
('3', 'three')
But can Joomla's own functions achieve the same thing in a single query? Currently I am doing a loop to insert each row (same table) in separate query. Not a good idea when dealing with tons of rows at once.
In your model you can do this:
$db = $this->getDBO();
$query = "
INSERT INTO x (a,b)
VALUES
('1', 'one'),
('2', 'two'),
('3', 'three')
";
$db->setQuery($query);
$db->query();
If you are outside your model you need to get the DB object like so:
$db = JFactory::getDBO();
You can use:
$db = JFactory::getDbo();
$query = $db->getQuery(true); // !important, true for every new query
$query->insert('#__table_name'); // #__table_name = databse prefix + table name
$query->set('`1`="one"');
$query->set('`2`="two"');
$query->set('`3`="three"');
/* or something like this:
$query->columns('`1`,`2`,`3`');
$query->values('"one","two","three"');
*/
$db->setQuery($query);
$db->query();
and $db->insertId() can return you autoinc id if you have one.
Try this, if you have values in an array :
$query = $this->db->getQuery(true);
$query->insert($this->db->quoteName('#__table_name'));
$query->columns($this->db->quoteName(array('col_1','col_2','col_3','col_4')));
for($i=0; $i < lengthOfArray; $i++)
{
$values= $arr_1[$i].','.$this->db->quote($arr_2[$i]).','.$this->db->quote($arr_3[$i]).','. $arr_4[$i];
$query->values($values);
}
$this->db->setQuery($query);
$result = $this->db->query();
You don't need $db = $this->getDBO();
just use this:-
$query = "
INSERT INTO x (a,b)
VALUES
('1', 'one'),
('2', 'two'),
('3', 'three')
";
$this->_db->setQuery($query);
$this->_db->query();
Try this:
$db = JFactory::getDbo();
$query = $db->getQuery(true);
$query->insert('x');
$query->columns('a,b');
$query->values('1', 'one');
$query->values('2', 'two');
$query->values('3', 'three');
$db->setQuery($query);
$db->query();
A description of "values" method
Adds a tuple, or array of tuples that would be used as values for an INSERT INTO statement.
Usage:
$query->values('1,2,3')->values('4,5,6');
$query->values(array('1,2,3', '4,5,6'));
In latest version of Joomla!, you can use it's own DB class as follows. Remember to use 'quoteName()' and 'quote()' functions as you needed.
$dbo = JFactory::getDbo();
$query = $dbo->getQuery(true);
$columns = array('col_one','col_two', 'col_three');
$values = array();
//if you need, here you can use forloop/foreach loop to populate the array
$values[] = 'val_1, val_2, val_3'; // first row values
$values[] = 'val_4, val_5, val_6'; // second row values
...
$query->insert($dbo->quoteName('#__table_name'));
$query->columns($columns);
$query->values($values);
$dbo->setQuery($query);
$dbo->query();
Hope this saves your time. Thanks. Happy coding! :)
...
$columns = array('user_id', 'type', 'object', 'lvl', 'date');
$values = array();
foreach ($batch as $row) {
$array = array(
$row->user_id,
$db->quote($row->type),
$db->quote($row->object),
$db->quote($row->lvl),
$db->quote($row->date),
);
$values[] = implode(',', $array);
}
$query->insert($db->quoteName('#activity_log'));
$query->columns($db->quoteName($columns));
$query->values($values);
$db->setQuery($query);
$result = $db->execute();

Resources