x
 
Create New Page

Revision: Queries

Revision from: 18:52, 19 Aug 2006

Queries enable you to pull information from your database using SQL. A good place to practice writing queries is control panel/admin/sql manager/database query/. If the query works there, you can use it on your pages with the Query Module, which enables you to invoke a query with an EE tag.

For example, here is a query to display all comments from all weblogs:

<ul>
{exp:query sql="SELECT * FROM exp_comments "}
<li>{name}-{comment}</li>
{/exp:query}
</ul>

You could restrict comments by author, for example, only showing comments from authors with id numbers 1 and 4:

<ul>
{exp:query sql="SELECT * FROM exp_comments WHERE author_id IN (1, 4)"}
<li>{name}-{comment}</li>
{/exp:query}
</ul>

Or you could show comments only from a certain weblog:

<ul>
{exp:query sql="SELECT * FROM exp_comments WHERE weblog_id='3'"}
<li>{name}-{comment}</li>
{/exp:query}
</ul>

You can also restrict what you are seeing based on a particular field such as comment_id and restrict it to show only the lastest five entries:

<ul>
{exp:query sql="SELECT * FROM exp_comments order by comment_id desc limit 5"}
<li>{name}-{comment}</li>
{/exp:query}
</ul>

You can also use an EE tag to make the search depend on the contents of the segment variables. For example, if the current user’s id is in {segment_3}, to show them all their comments you could use:

<ul>
{exp:query sql="SELECT * FROM exp_comments WHERE author_id='{segment_3}'"}
<li>{name}-{comment}</li>
{/exp:query}
</ul>

Unfortunately, not all variables can be included in the query in this manner—for example, in EE 1.2,

... WHERE author_id='{member_id}' ...

does not work.

More complicated queries will require using SQL JOINs. For an example, try this (also linked under “S” below).

Category:Queries

Categories: