PHP loop to echo all Joomla article id's - php

With my very basic PHP knowledge I'm trying to make a module for Joomla V1.5. I am not quite into all the Joomla classes and methods but perhaps you can help me out.
What I'm trying to do is create a php loop which echo's all the article id's (and some html) from a certain category.
Normally I would do this by calling on the content table from the Joomla db but to make the code a bit more tidy I want to use the Joomla classes for this.
Can anyone point me the right direction which classes and methods to use for this?

There are no classes for handling the selection of the articles.
So it comes down to using a query and looping through the result set:
$catId = 59; // the category ID
$query = "SELECT * FROM #__content WHERE catid ='" . $catId . "'"; // prepare query
$db = &JFactory::getDBO(); // get database object
$db->setQuery($query); // apply query
$articles = $db->loadObjectList(); // execute query, return result list
foreach($articles as $article){ // loop through articles
echo 'ID:' . $article->id . ' Title: ' . $article->title;
}

Related

How to Display Joomla database table using native joomla 2.5 php objects

I am trying to display data from a MySQL database table using the native joomla PHP objects, however I can never get it to work right. It never displays any data.
I know how to display the data by connecting to the database the old fashion way, like below...
$con = mysqli_connect("localhost","xxxxxx_user10","$dbpass","xxxxxxx_final");
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
} else {
//What is the base model
$sku = $finish;
// Select The Correct Table
$result = mysqli_query($con,"SELECT * FROM BAH_finish WHERE color_value='$sku' GROUP BY uniqueID ORDER BY uniqueID ASC");
$row = mysqli_fetch_array($result);
$finishname = $row['color_name'];
$finishtype = $row['color_type'];
However i'd like to display content like I have above, but by using the joomla native php objects, so iv'e created a sample php table with the following fields.....
| ID | Last | First | Address | City | State | ZIP
and tried to display it (ALL ROWS) / OR (ONE ROW) using the following joomla code.....but nothing happens....no matter how I try to switch it up or change out parts of the code....So my thinking is that i'm missing a fundamental part of how this should work....Thanks again for your help! Also please do not quote joomla 2.5 component tutorial from joomla.org...that is where I've gotten this code and IMO it lacks a lot of information.
<?php
// Get a db connection.
$db = JFactory::getDbo();
// Create a new query object.
$query = $db->getQuery(true);
// Select all records from the user profile table where key begins with "custom.".
// Order it by the ordering field.
$query->select($db->quoteName(array('Last', 'First', 'Address', 'City', 'State', 'ZIP')));
$query->from($db->quoteName('111testnames'));
$query->where($db->quoteName('Last') . $db->quote('buffet'));
// Reset the query using our newly populated query object.
$db->setQuery($query);
// Load the results as a list of stdClass objects (see later for more options on retrieving data).
$results = $db->loadObjectList();
echo $results;
?>
You have to correct: $query->from($db->quoteName('111testnames'));
to $query->from($db->quoteName('#__111testnames'));
using #__ automatically adds the suffix of your table.
Another error that I could see is the where clause doesn't have have an operator. Please try to correct it to $query->where($db->quoteName('Last') ." = ". $db->quote('buffet'));.
In order to have a proper view of the results you have to use print_r($results); instead of echo $results; as there is an object array you have to display not a string.
Good Luck!

Trying to Find the Best way to pull DB item in Joomla 2.5 Component

I have a database which has 2 columns id and title. What is the best way for me to filter through these table values to display the matching title results when a user submits the id value in a form for a Joomla 2.5 component (admin view)?
When I look at the documentation here:
http://docs.joomla.org/Selecting_data_using_JDatabase
I see that by using Joomla’s API I can use a shorthand to create this connection. I have tried:
$userSubmittedIDValue = $_GET["userSubmittedIDValue"];
// Get a db connection.
$db = JFactory::getDbo();
// Create a new query object.
$query = $db->getQuery(true);
$query
->select($db->quoteName(array('title')))
->from($db->quoteName('#__mycomponent_table'))
->where($db->quoteName('id') . ' = '. $db->quote('$userSubmittedIDValue'))
$results = $db->loadObjectList();
Unfortunately, this gives the following error:
Parse error: syntax error, unexpected T_VARIABLE
Then the error points to $results = $db->loadObjectList();
I just need to pull that value and apply it to a php variable so that I can use it as required. Any ideas?
Okay thanks to the first answer I have realized that I was missing a semi-colon. The trouble I am having now is still in pulling the value from the array using foreach. I have tried adding the following:
foreach (array($results) as $userSubmittedIDValue) {
echo $results;
}
But this just prints the word Array. I am getting close, but something is still off.
You're getting that error due to the fact you have a missing semi colon after your query.
So, change this:
->where($db->quoteName('id') . ' = '. $db->quote('$userSubmittedIDValue'))
to this:
->where($db->quoteName('id') . ' = '. $db->quote('$userSubmittedIDValue'));
Simply note the ; on the end
Once done, you can use a foreach loops to display your results.
So your final code to use would be this:
$db = JFactory::getDBO();
$query = $db->getQuery(true);
$query->select('*')
->from('#__mycomponent_table')
->where($db->quoteName('id') . ' = '. $db->quote($userSubmittedIDValue));
$db->setQuery($query);
$rows = $db->loadObjectList();
foreach ($rows as $row) {
echo $row->title;
}
I completely forgot to mention before that you also have to remove the single quote wrapped around $userSubmittedIDValue in the query as shown in my code above.
Hope this helps

How to get intro image path of an article from db in Joomla

I am developing a new module which will show up the featured items on the slider.
I have successfully get the data in my module but for intro image there is problem.
My query is here:
// Get a db connection.
$db = JFactory::getDbo();
// Create a new query object.
$query = $db->getQuery(true);
$query
->select(array('f.content_id', 'c.id', 'c.title', 'c.alias', 'c.images'))
->from('#__content AS c')
->join('INNER', '#__content_frontpage AS f ON (c.id = f.content_id)')
->where("c.language = '" . JFactory::getLanguage()->getTag() . "' AND c.state=1")
->order('f.ordering ASC');
// Reset the query using our newly populated query object.
$db->setQuery($query);
// Load the results as a list of stdClass objects.
$results = $db->loadObjectList();
foreach ($results as $r)
{
$imagePath = $r->images;
//.
//.
//.
}
As you know image paths are kept in images column in contents table like the following form:
{
"image_intro":"images\/products\/201191420496.jpg",
"float_intro":"",
"image_intro_alt":"",
"image_intro_caption":"",
"image_fulltext":"",
"float_fulltext":"",
"image_fulltext_alt":"",
"image_fulltext_caption":""
}
I want to know how to extract the intro image path from this data. Is there a common function/method for this or should I go with PHP's explode() function?
Finally someone has already made a good solution for this.
There is a good function of PHP, json_decode().
It converts that string (which I have learned later that it is JSON) into a key-value array. So all the data gets reachable:
$pictures = json_decode('{"image_intro":"images\/products\/201191420496.jpg",
"float_intro":"",
"image_intro_alt":"",
"image_intro_caption":"",
"image_fulltext":"",
"float_fulltext":"",
"image_fulltext_alt":"",
"image_fulltext_caption":""
}',
true);
echo $pictures['image_intro']; //gives images/products/201191420496.jpg

Joomla using DISTINCT in mySQL call

I'm trying to use DISTINCT to get a list of cities from a column in my DB.
function cityData() {
$db =& JFactory::getDBO();
$query = "SELECT DISTINCT MSTCITY FROM " . $db->nameQuote('#__mls') . " ORDER BY MSTCITY;";
$db->setQuery($query);
$tbl = $db->loadObjectList();
return $tbl;
}
Is there something akin to loadObjectList() that I can use ?
There are several options available to get data using database object.
You can check this link- http://docs.joomla.org/Accessing_the_database_using_JDatabase/1.5
In your case you can use loadResultArray() in place of loadObjectList.It'll return list of cities as values of an array.
Here's the revised joomla resource page for version 2.5 and 3.x
Selecting data using JDatabase. Also since you're already using the loadObjectList() function this question may be better asked as
How to use DISTINCT and JDatabase together
This post has a good solution by Janga_Jack but for your example here's a Joomla 3.x way to accomplish what you need, that allows you to use the convenience methods quote() or q(), quoteName() or qn(), and especially escape() or e().
function cityData() {
$db =& JFactory::getDBO();
$query = $db->getQuery(true);
$fieldlist = $db->qn(array('mls.MSTCITY')); // add the field names to an array
$fieldlist[0] = 'distinct ' . $fieldlist[0]; //prepend the distinct keyword to the first field name
$query->select($fieldlist);
->from($db->qn('#__mls', 'mls'))
->order($db->qn('mls.MSTCITY'));
$db->setQuery($query);
$tbl = $db->loadObjectList();
return $tbl;
}

Include within a while loop

I'm sure my inability to solve this problem steams from a lack of knowledge of some aspect of php but I've been trying to solve it for a month now with no luck. Here is a simplified version of the problem.
In my database I have a members table, a childrens table (the children of each member), and a friend requests table (this contains the friend requests children send to each other).
What I'm attempting to do is display the children of a particular parent using the following while loop....
$query = "SELECT * From children " . <br>
"WHERE parent_member_id = $member_id"; <br>
$result = mysql_query($query) <br>
or die(mysql_error());<br>
$num_children = mysql_num_rows($result);<br>
echo $num_children;<br>
while($row = mysql_fetch_array($result)){<br>
$first_name = $row['first_name'];<br>
$child_id = $row['child_id'];<br>
<div>echo $first_name<br>
}
This while loop works perfectly and displays something like this...
1) Kenneth
2) Larry
What I'm attempting to do though is also display the number of friend requests each child has next to their name...like this
Kenneth (2)
Larry (5)
To do this I attempted the following modification to my original while loop...
$query = "SELECT * From children " .<br>
"WHERE parent_member_id = $member_id";<br>
$result = mysql_query($query) <br>
or die(mysql_error());<br>
$num_movies = mysql_num_rows($result);<br>
echo $num_movies;<br>
while($row = mysql_fetch_array($result)){<br>
$first_name = $row['first_name'];<br>
$child_id = $row['child_id'];<br>
echo $first_name; include('counting_friend_requests.php') ;
}
In this version the included script looks like this...
$query = "SELECT <br>children.age,children.child_id,children.functioning_level,children.gender,children.parent_member_id,children.photo, children.first_name,friend_requests.request_id " .
"FROM children, friend_requests " .
"WHERE children.child_id = friend_requests.friend_two " .
"AND friend_requests.friend_one = $child_id"; <br>
$result = mysql_query($query)<br>
or die(mysql_error());<br>
$count = mysql_num_rows($result);<br>
if ($count==0)<br>
{<br>
$color = "";<br>
}<br>
else<br>
{<br>
$color = "red";<br>
}<br>
echo span style='color:$color' ;<br>
echo $count;<br>
echo /span;<br>
Again this while loop begins to work but the included file causes the loop to stop after the first record is returned and produces the following output...
Kenneth (2)
So my question is, is there a way to display my desired results without interrupting
the while loop? I'd appreciate it if anyone could even point me in the right direction!!
Avoid performing sub queries in code like the plague, because it will drag your database engine down as the number of records increase; think <members> + 1 queries.
You can create the query like so to directly get the result you need (untested):
SELECT child_id, first_name, COUNT(friend_two) AS nr_of_requests
From children
LEFT JOIN friend_requests ON friend_one = child_id OR friend_two = child_id
WHERE parent_member_id = $member_id
GROUP BY child_id, first_name;
It joins the children table records with friend_requests based on either friend column; it then groups based on the child_id to make the count() work.
You don't need to include the php file everytime you loop. Try creating a Person class that has a method getFriendRequestCount(). This method can all the database. This also means you can create methods like getGriendRequests() which could return an array of the friend requests, names etc. Then you could use count($myPerson->getFriendRequests()) to get the number. Thousands of options!
A great place to start, http://php.net/manual/en/language.oop5.php
Another example of a simple class, http://edrackham.com/php/php-class-tutorial/
Eg.
include ('class.Person.php');
while(loop through members)
$p = new Person(member_id)
echo $p->getName()
echo $p->getFriendRequestCount()
foreach($p->getFriendRequests as $fr)
echo $fr['Name']
In your Person class you want to have a constructor that grabs the member from the database and saves it into a private variable. That variable can then be accessed by your functions to proform SQL queries on that member.
Just to clarify whats happening here.
"include" processing is done when the script is parsed. Essentially its just copying the text from the include file into the current file. After this is done the logic is then parsed.
You should keep any include statements separate from you main logic. In most cases the "include"d code will contain definitions for one or more functions. You can then call these functions from the main body of your program at the appropriate place.

Categories