How do I set the order when querying from DB? - php

I'm trying to query from a DB to get joomla articles from a certain category (52), and that are published.
I want to return these as the newest created, but I don't know where to add in the ORDER BY for the query.
I did try to add ->orderby('created'); just above $db->setQuery($query); but that didn't seem to work, it still only seems to be displaying by ascending order of ID.
Can anyone help?
<?php
$i = 0;
$db = JFactory::getDbo();
$query = $db->getQuery(true);
$query->select('*')
->from('#__content')
->where('catid = 52 AND state = 1');
$db->setQuery($query);
$rows = $db->loadObjectList();
foreach ( $rows as $row ) {
if(++$i > 1) break;
echo "<li><a href='/why-us/news/".$row->id."-".$row->alias."'>".$row->title."</a></li>";
}
?>

You can simply use ->order('created DESC') to achieve your desired results.
Check the documentation page, here

Related

Sorting/Limiting Table List MySQL and PHP

I want to make select and print out all of the tables I have (I got that so far), and then limit it using `` and then ordering them by table name, and have 10 results per page.
How would I go about doing that? I know how to do it getting data from tables, but I don't know how to do it using just tables.
I have this so far:
function list_tables($type){
$sql = "SHOW TABLES FROM example";
$result = mysql_query($sql);
while($row = mysql_fetch_row($result)){
$table_name = $row[0];
echo $table_name; //edited out a lot to keep it simple
//I'm just printing out a lot of data based on table name anyway
}
mysql_free_result($result);
}
So far, it only prints out all of the table names (+ extra info I print for table names) all in the same page and it's getting the the point where it takes forever to scroll. I'd like to limit it to about 10-20 posts per page instead of a few hundred posts on one page.
Thanks in advanced if anyone can help me. Much appreciated.
Calculate the offset and limit according to the page number and try the below query:
function list_tables($type, $offset, $limit){
$sql = "SELECT TABLE_NAME FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_SCHEMA = 'example' ORDER BY TABLE_NAME LIMIT $offset, $limit";
$result = mysql_query($sql);
while($row = mysql_fetch_row($result)){
$table_name = $row[0];
echo $table_name; //edited out a lot to keep it simple
//I'm just printing out a lot of data based on table name anyway
}
mysql_free_result($result);
}
Use below given query which supports LIMIT so you can do pagination with your table names.
select * from information_schema.tables LIMIT 5
i did this:
function list_tables(){
$amtperpage = 15;
$sql = "SELECT COUNT(TABLE_NAME) FROM information_schema.tables WHERE TABLE_SCHEMA = 'my_dbname'";
$result = mysql_query($sql);
$row = mysql_fetch_row($result);
$total_rows = $row[0];
//pagination stuff here
if(isset($_GET['p'])) $curpage = intval($_GET['p']); else $curpage=1;
$start = abs(($curpage-1)*amtperpage);
$sql = "SELECT TABLE_NAME FROM information_schema.tables ORDER BY TABLE_NAME ASC LIMIT $start,$per_page";
$res = mysql_query($sql);
while($row=mysql_fetch_array($res)) $DATA[++$start]=$row;
$uri = strtok($_SERVER['REQUEST_URI'],"?")."?";
$tmpget = $_GET;
unset($tmpget['p']);
if($tempget){
$uri .= http_build_query($tmpget)."&";
}
$num_pages=ceil($total_rows/$amtperpage);
for($i=1;$i<=$num_pages;$i++) $PAGES[$i]=$uri.'p='.$i;
?><div id="container">Pages:
foreach ($PAGES as $i => $link){
if($i == $curpage){
=$i
} else {
?><?=$i?>
}
} ?>
foreach($DATA as $i => $row){
$table_name = $row[0];
//use my functions to get data for each table name and list it and such
}
}
this is highly butchered since I have a lot of stuff that would've gotten in the way of the point but this should work. Thanks to the people who helped me. :)

Joomla doesn't work with PDO connection

Hey guys I need your help I have this code in a localhost file :
$db = new PDO('mysql:host=localhost;dbname=db;charset=utf8', 'user', 'pass');
$data = array();
$results = $db->query("SELECT * from YOUR_TABLE_NAME");
while ($row = $results->fetch(PDO::FETCH_ASSOC)) {
$data[$row['prov_name']][] = $row;
}
But when I try to integrate this file in Joomla it doesn't work! Do you know how can I "transform" this into Joomla connection?
I always use this one for some select
$db =& JFactory::getDBO();
$query = 'SELECT CA_id FROM compras_activos where STAT_name = "Solicitado"';
$db->setQuery($query);
$result = $db->loadObjectList();
$CA_id = $result[0];
But that is just for one specific value but now I need all(*) the table.
Thanks
You should really read the documentation that I provided. If you are able to write a query as shown in your question, then this should not be too taxing. You can use the following:
$db = JFactory::getDbo();
$query = $db->getQuery(true);
$query->select($db->quoteName('*'))
->from($db->quoteName('#__compras_activos'))
->where($db->quoteName('STAT_name') . ' = '. $db->quote('Solicitado'));
$db->setQuery($query);
$result = $db->loadObjectList();
If your database table do not belong to an extension associated with Joomla, then remove the #__ prefix in the above code.
Hope this helps

PHP SQL Joomla store table with two columns into array and echo them later

So I have a simple table with two columns. The table is called "mytable" and the columns are "product" and "id". The table has about 12 entries.
$db = JFactory::getDbo();
$query = "SELECT * FROM mytable";
$db->setQuery($query);
$results = $db->loadObjectList();
So I've gotten this far querying successfully but I want to call back the results of each row. That's the part I am stuck on. I need to store this into an array so I can later make a while loop spitting out each row. Also I cannot echo it right underneath that code. This needs to be stored in an array that is then pulled from another page and then I spit out each row. Thanks!
Try this,
$db = JFactory::getDbo();
$query = "SELECT * FROM mytable";
$db->setQuery($query);
$results = $db->loadObjectList();
echo '<pre/>'
print_r($results);//the resulted array is already in this variable you can iterate it later with foreach loop.
for looping and printing
foreach($results as $key=>$value){
echo 'Product-->'.$value->product;
echo 'ID-->'.$value->id;
}
check the Joomla DB query for more details.
Hope it helps..
I would personally use more up to date coding standards for you query, like so:
$db = JFactory::getDbo();
$query->select($db->quoteName('*'))
->from($db->quoteName('mytable'));
$db->setQuery($query);
$results = $db->loadObjectList();
Then to get the results, create a loop:
foreach($results as $result) {
echo 'ID = ' . $result->id;
echo 'Product = ' . $result->product;
}
Hope this helps

How to query a database with an array outside a loop

Hie. I am trying not to place an SQL query inside a loop, since this improves performance. I think I am supposed to use implode. But can't figure out how to do it. Here is my code:
<?php
//FUNCTION CONNECTNG TO DB HERE
function turn_result_to_array($result)
{
$result_array = array();
for ($count=0; $row = mysql_fetch_array($result); $count++)
{
$result_array[$count] = $row;
}
return $result_array;
}
function get_sender_username()
{
//connect to DB
$query = sprintf("SELECT DISTINCT sender FROM direct_messages
WHERE receiver_username='%s'
ORDER BY direct_messages.id DESC",
mysql_real_escape_string($_COOKIE['username']));
$result = mysql_query($query);
$result = turn_result_to_array($result);
return $result;
}
$senders = get_sender_username();
foreach($senders as $sender)
{ //SELECT IMAGE(S) FROM USER TABLE WHERE USERNAME = $SENDERS }
Instead of putting the query inside the FOREACH, i want to put it after, so i don't make multiple round trips to the database. FYI i already know that we supposed to switch to PDO. Thanks in advance.
Here is one way of doing it:
$senderInString = implode("','",$senders);
$senderInString = "('$senderInString')";
$newQuery = "SELECT something FROM tables WHERE sender in $senderInString;"
$newResult = mysql_query($newQuery);
Use
$query= "SELECT IMAGE(S) FROM USER TABLE WHERE USERNAME IN (".implode(',',$senders).")";
$result = mysql_query($query);
In the place of foreach

inner join query in joomla

I want to fire one complex query in my joomla site. I have written below code for it.
$db = JFactory::getDbo();
$query = $db->getQuery(true);
$query->select('`chr`.`characteristic_id`,`chr`.`characteristic_value`,`prc`.`price_value`');
$query->from('`#___hikashop_product` AS `pdt`');
$query->join('inner', '`#__hikashop_variant` AS `vari` ON `pdt`.`product_id` = `vari`.`variant_characteristic_id`');
$query->join('inner', '`#__hikashop_characteristic` AS `chr` ON `vari`.`variant_characteristic_id` = `chr`.`characteristic_id`');
$query->join('inner', '`#__hikashop_price` AS `prc` ON `pdt`.`product_id` = `prc`.`price_product_id`');
$query->where('`pdt`.`product_id` = 68');
$db->setQuery($query);
Query is executing in my local mysql.
any help will be appreciated
You can try this
$db->setQuery("Your query");
$result = $db->query();
//if you need the count
$rowcount = $db->getNumRows();
//if the result is multiple rows
$result_array = $db->loadAssocList() or $db->loadObjectList();
//if the result is single row you can use
$result = $db->loadAssoc() or $db->loadObject();
To fire the query, all you need to do is:
$rows = $db->loadAssocList(); // or loadObjectList()
The above will put all of the rows into $rows
You can also fire the query without grabbing the rows with:
$db->query();

Categories