Zend Framework - applying order by on a nested query - zend-framework

This might be a very simple thing. Check out the normal sql query below
(select * from shopping order by shopping_id desc limit 5) order by RAND()
This query runs successfully in mysql - not sure if this is the right way of doing it - but it works. It gets the last 5 ids from shopping table and randomly orders them everytime
I want to achieve this in Zend. I'm not sure how to execute the first part and then apply the RAND clause to the results - what I have below does not do that.
$select = $this->select()
->from(array('sh'=>'shopping'))
->order('shopping_id desc')
->limit(5)
->order('RAND()');

Why not take a slightly different approach which will acheive the same results. If you drop the subselect and the order by RAND() you can get the rows very quickly from the database, then when you are working with the rows, you could always randomize them.
$select = $this->select()
->from(array('sh'=>'shopping'))
->order('shopping_id desc')
->limit(5)
$rows = $this->fetchAll($select);
// take it from a rowset object, convert to an array:
$rowArray = array();
foreach ($rows as $row) $rowArray[] = $row;
shuffle($rowArray);

The Zend_Db_Expr class lets you do that. You create a new instance of the Zend_Db_Expr class and using its constructor you pass in the expression as a string: "RANDOM()".
$select = $this->select()
->from(array('sh'=>'shopping'))
->order('shopping_id desc')
->limit(5)
->order(new Zend_Db_Expr('RANDOM()'));

Related

Add a single field to model using raw SQL

I'm developing an extension for TYPO3 CMS 8.7.8. I'm using query->statement() to select all fields from a single table, plus 1 field from another table. I get a QueryResult with the proper models and I would like to have that 1 extra field added to them. Is that possible?
You can do SQL queries with the ->statement(...) method and in that, use normal JOIN commands
From the documentation
$result = $query->statement('SELECT * FROM tx_sjroffers_domain_model_offer
WHERE title LIKE ? AND organization IN ?', array('%climbing%', array(33,47)));
So you can do JOINs on whatever table you want to (also code from the documentation)
LEFT JOIN tx_blogexample_person
ON tx_blogexample_post.author = tx_blogexample_person.uid
But you will end up with the raw data from the mysql query. If you want to transform it into a object, use the Property Mapper
You can use JOIN in your sql statments like below.
$query = $this->createQuery();
$sql = 'SELECT single.*,another.field_anme AS fields_name
FROM
tx_single_table_name single
JOIN
tx_another_table_name another
ON
single.fields = another.uid
WHERE
O.deleted = 0
AND O.hidden=0
AND O.uid=' . $orderId;
return $query->statement($sql)->execute();

Multiple DB update query using Laravel 5

I'm new in Laravel and I'm trying to update mysql table's multiple rows using one query. I need to update for example 100 rows like this:
$q = \DB::table('exmaple')
->where('exampleID', $array)
->update(array('Viewed' => 1));
$array is array with ID-s.
I have try also to implode array to string, then execute query, but with no result. Can anyone help?
Does this work for you:
$q = \DB::table('example')
->whereIn('exampleID', $array)
->update(array('Viewed' => 1));
whereIn() accepts an array as a second parameter so all IDs in this array will be affected by the query.

get most actual row with zend's fetchRow

I'm very new to zend (1.12)..so please excuse my very basic question:
I want to fetch only one row from a database. Thatfore I want to use the fetchRow(..) function like this
$row = $db->fetchRow($db->select()->where("col1 = '".val1."' AND col2='".val2."'"));
The problem is, that there may be many rows that fit to the where-clause and I only want to get the one with the highest id. How can I do this?
The fetchRow() method returs only one row. If you want to choose row with the highest ID meeting other conditions, invoke it like this:
$select = $db->select()
->where('col1 = ?', $val1)
->where('col2 = ?', $val2)
->order('id DESC');
$row = $db->fetchRow($select);
Also, remember to pass values to SQL query in the way as in above code (to avoid SQL injection attack risk).

How to choose which comes first when specifying OR in MySQLi SELECT statement

When you retrieve data through a MySQLi statement such as the following:
$sqls = "SELECT * FROM course WHERE course='$product_id_array' OR course='Both' ORDER BY ...";
$sqlsresults = mysqli_query($db_conx,$sqls);
while($row = mysqli_fetch_assoc($sqlsresults)) {
$selectedContent = $row["content"];
$selectedTitle = $row["title"];
}
Is there a way to output the match for 'both' first? Would this be as simple as re-arranging the order of the WHERE portion of the statement?
Your ORDER BY explicitly sorts only by id. There is no way around this in the WHERE part of your query. To change how results are ordered, use ORDER BY.
SELECT *
FROM course
WHERE course=...
OR course='Both'
ORDER BY CASE course WHEN 'Both' THEN 0 ELSE 1 END ASC, id DESC
Unrelated note: if $product_id_array contains untrusted user input, the user can put things like '; DELETE FROM course; -- in there. Read up on parameterized queries to learn how to prevent that.

Best way to do an Inner Join using the Zend Framework?

It seems like there's a few different ways to join two tables using the Zend Framework, but I've never done it before so I don't know which is the best way to do it.
This is what I'm trying to do...
I have 3 tables in my database:
users
( id , name )
groups
( id , name )
group_members
( id , group_id , user_id )
I'm trying to look up the groups that a user belongs to and display that to the user. This SQL statement pretty much does the job (though there may be a better way to write it). It only returns the columns I'm concerned with which are the group's id and title.
SELECT groups.id, groups.title
FROM group_members
INNER JOIN groups
ON groups.id = group_members.group_id
WHERE user_id = $userId
How can I do this with the Zend Framework?
Finally figured out how to do it. If you've got a better way, please let me know.
$db = Zend_Db_Table::getDefaultAdapter(); //set in my config file
$select = new Zend_Db_Select($db);
$select->from('groups', array('id', 'title')) //the array specifies which columns I want returned in my result set
->joinInner(
'group_members',
'groups.id = group_members.group_id',
array()) //by specifying an empty array, I am saying that I don't care about the columns from this table
->where('user_id = ?', $userId);
$resultSet = $db->fetchAll($select);
This will return a table with only the id and title columns. The empty array() was the key to removing the columns I didn't care about. I could then do something with the result set.
foreach ($resultSet as $row) {
//do something with $row->id or $row->title
}
No need to using Join,we can use Zend_Db_Table instead for the reason about the MVC pattern. I got this idea form here,#10 by Filip.(maybe they call this "Table Data Gateway"?)