Joomla query Object (stdClass) with random - php

I'm building a Joomla template. For this I need to test/query two fields in the DB. I'm trying to get familiar with getDBO class but stuck here.
These two queries do nearly the same. I need both variables $category and $hasField. How can merge these two queries into one? This is a bit redundant.
$db = JFactory::getDBO();
$id = JRequest::getInt('id');
$db->setQuery('
SELECT
#__categories.title
FROM
#__content,
#__categories
WHERE
#__content.catid = #__categories.id
AND
#__content.id = '.$id
);
$category = $db->loadResult();
$db->setQuery('
SELECT
#__attachments.filename,
#__attachments.parent_id
FROM
#__attachments
WHERE
#__attachments.parent_id =' . $id
);
$hasField = $db->loadResult();

You can try joining #__attachments to the 1st query.
SELECT
#__categories.title,
#__attachments.filename,
#__attachments.parent_id
FROM
#__content,
#__categories,
#__attachments
WHERE
#__content.catid = #__categories.id
AND
#__attachments.parent_id = #__content.id
AND
#__content.id = $id

I might be wrong there as no place to test but it suppose to be like left joined:
SELECT
#__categories.title, atch.filename
FROM
#__content,
#__categories
LEFT JOIN
#__attachments AS atch ON atch.parent_id = #__content.id
WHERE
#__content.catid = #__categories.id
AND
#__content.id = '.$id
);

Related

Using an sql query result as a search term for a new sql statement

So I am trying to use a result from an SQL search $search_course and then having that as the WHERE LIKE part of the next statement $Search_Module.
once the $Search_Module query has finished I would like the results to be in a list which I know should be coded correctly.
I have tried the following code but the search returns no values;
Any help with this would be much appreciated, thanks in advance.
$search_course = "
SELECT title, id, wyl, overview, module, course, careers
FROM course
LEFT JOIN cm
ON course.id=cm.course
WHERE id LIKE '%".$_POST['submitcourseselection']."%'";
$result = $mysqli->query($search_course) or die($mysqli->error);
$display_course = $result->fetch_assoc();
//Searches the module table in the DB for modules within the course
$Search_Module = "
SELECT id, title, level, credits
FROM module
WHERE id LIKE '".$search_course['module']."'";
$M_Results = $mysqli->query($Search_Module) or die($mysqli->error);
$ModuleList = '';
while ($MResults = $M_Results->fetch_assoc()) {
$ID = $MResults['id'];
$Title = $MResults['title'];
$Level = $MResults['level'];
$Credits = $MResults['credits'];
$ModuleList.='<div><h2>'.$Title.'</h2></div>';
}
you don't need LIKE in your second query and you can do all by one query.
$search_course = "
SELECT id, title, level, credits
FROM module
WHERE id IN (SELECT module
FROM course
LEFT JOIN cm
ON course.id=cm.course
WHERE id LIKE '%".$_POST['submitcourseselection']."%'")";
in your where clause WHERE id LIKE '".$search_course['module']."'";, you are referencing an array location of a string $search_course, which is your SQL statement.
I think you meant to reference your result array $display_course, so try this:
$search_course = "
SELECT title, id, wyl, overview, module, course, careers
FROM course
LEFT JOIN cm
ON course.id=cm.course
WHERE id LIKE '%".$_POST['submitcourseselection']."%'";
$result = $mysqli->query($search_course) or die($mysqli->error);
$display_course = $result->fetch_assoc();
//Searches the module table in the DB for modules within the course
$Search_Module = "
SELECT id, title, level, credits
FROM module
WHERE id LIKE '".$display_course['module']."'";
$M_Results = $mysqli->query($Search_Module) or die($mysqli->error);
$ModuleList = '';
while ($MResults = $M_Results->fetch_assoc()) {
$ID = $MResults['id'];
$Title = $MResults['title'];
$Level = $MResults['level'];
$Credits = $MResults['credits'];
$ModuleList.='<div><h2>'.$Title.'</h2></div>';
}

How do I do a Propel query with 3 tables or more?

I want to do this:
SELECT * FROM `mydb`.`table1`
INNER JOIN `mydb`.`table2`
ON `table2`.`table1_id` = `table1`.`id`
INNER JOIN `mydb`.`table3`
ON `table3`.`id` = `table1`.`table3_id`
WHERE `table2`.`myfield2`='string1'
AND `table3`.`myfield3` = 'string2';
query on Propel, but can't find the right way to do it. With only two tables join() seems to work fine like this
$query = Table1Query::create()
->join('Table2')
->where('Table2.myfield2 = ?', $string1)
->filterByMyfield3($string2)
->findOne();
But how does it work with three or more tables?
Of course it is possible. You have described the mapping in a config file.
Example :
$review = ReviewQuery::create()
->joinWith('Review.Book')
->joinWith('Book.Author')
->joinWith('Book.Publisher')
->findOne();
$book = $review->getBook()
$author = $book->getAuthor();
$publisher = $book->getPublisher();
http://propelorm.org/documentation/04-relationships.html

Getting data from 2 related and 1 unrelated MySQL tables with one query?

I am trying to create an archives page for my blog, which is also still being built. I have three different MySQL tables I need to pull data from and 1 of them is unrelated from the other 2. I found a similar post here but seeing as how I am not very experienced with PHP I am not able to figure out how to convert that to what I need. I know this can easily be done by executing three different queries, but that will put an unnecessary load on the server and slow down page load times and everything else.
The 2 related categories are "blogs" and "categories" while the third is for a different application built into the blog called the "Brain Link"
Here are the two queries for the related tables:
$blogQuery = mysqli_query($link, "SELECT * FROM pub_blogs ORDER BY id DESC") or die ("Could not access DB: " . mysqli_error($link));
$row = mysqli_fetch_assoc($blogQuery);
$blogID = $link->real_escape_string($row['id']);
$title = $link->real_escape_string($row['title']);
$date = $link->real_escape_string($row['date']);
$category = $link->real_escape_string($row['category']);
$content = $link->real_escape_string($row['content']);
$blogID = stripslashes($blogID);
$title = stripslashes($title);
$date = stripslashes($date);
$category = stripslashes($category);
$content = stripslashes($content);
$catQuery = mysqli_query($link, "SELECT * FROM categories ORDER BY id DESC") or die ("Could not access DB: " . mysqli_error($link));
$row = mysqli_fetch_assoc($catQuery);
$catID = $link->real_escape_string($row['id']);
$catName = $link->real_escape_string($row['name']);
$description = $link->real_escape_string($row['descriptions']);
$catID = stripslashes($catID);
$catName = stripslashes($catName);
$description = stripslashes($description);
and here is the third unrelated query:
$brainQuery = mysqli_query($link, "SELECT * FROM brain_links ORDER BY id DESC") or die ("Could not access DB: " . mysqli_error($link));
$row = mysqli_fetch_assoc($brainQuery);
$brainID = $link->real_escape_string($row['id']);
$site_name = $link->real_escape_string($row['site_name']);
$site_url = $link->real_escape_string($row['site_url']);
$post_date = $link->real_escape_string($row['post_date']);
Is it possible to get data from all three of these with one query? If not can someone point me in the direction of somewhere that will tell me how to join the two related ones?
The blog table saves the category ID under the 'category' column to identify which category it belongs to
I appreciate any help or suggestions!
This will bring the data from two tables. How ever, from the third tables data can't be get
SELECT
*
FROM pub_blogs
LEFT JOIN categories on categories.id = pub_blogs .category
ORDER BY id DESC
Ajnd for the third table you can not get it because you can not make a link to any other table. If you change your table structure you can do it.
No you cant get data from 3 rd table using same query .
Mysql wants a mapping between two tables .
You can join the blog and category but not the brain links
For the first two tables do :
select * , c.id , c.name , c.descriptions from pub_blogs p join categories c on c.id = p.category order by id desc ;
For the third table as there is no mapping you cant join it .
Happy Coding :)

One query instead of two?

Here I'm making two queries with PHP. Is there something more simple? One query instead of two?
$id = mysql_real_escape_string($_GET["id"]);
$result = mysql_query("SELECT * FROM questionstable WHERE id=$id");
$row = mysql_fetch_assoc($result);
$category = $row['category'];
$main = mysql_query("SELECT name FROM categorytable WHERE id=$category");
SELECT questionstable.*, categorytable.name
FROM questionstable
INNER JOIN categorytable
ON categorytable.id = questionstable.category
WHERE questionstable.id=$id
As an aside, assuming your questionstable.id is numeric, you could use $id = (int)$_GET["id"] and save some writing. (It's also probably a safer bet. Just because it's escaped doesn't mean it's completely safe--especially when it's not within quotes [gives you a LOT of options for SQL injection]. ;-))
Please try:
SELECT name
FROM categorytable
WHERE id = (
SELECT category
FROM questionstable
WHERE id = $id
)
$id = mysql_real_escape_string($_GET["id"]);
$main = mysql_query("SELECT c.name FROM categorytable c inner join questionstable q on c.category = q.category WHERE q.id = $id");
Do not use inner join use left join instead, it won't return any result if the category is not found
SELECT questionstable.*, categorytable.name
FROM questionstable
LEFT JOIN categorytable
ON categorytable.id = questionstable.category
WHERE id=$id

Zend_Db_Select: Working with JOIN's

I have this query:
SELECT
groups.name
categories.name,
categories.label
FROM
groups
JOIN
categories
ON
(categories.group1 = groups.id
OR
categories.group2 = groups.id)
AND
groups.label = :section
AND
categories.active = 1
Now, this is my JOIN using Zend_Db_Select but it gives me array error
$select->from($dao, array('groups.name', 'categories.name', 'categories.label'))
->join(array('categories', 'categories.group1 = groups.id OR categories.group2 = groups.id'))
->where('groups.label = ?', $group)
->where('categories.active = 1');
My error:
Exception information:
Message: Select query cannot join with
another table
Does anyone know what I did wrong?
UPDATE / SOLUTION:
I've found the solution thanx to Eran. I just post the solution here in case anyone else is stuck on a problem like this one. The solution is:
$db = Zend_Registry::get('db');
$dao = new Default_Model_Db_CategoryDao('db');
$select = $dao->select();
$select->setIntegrityCheck(false)
->from(array('c' => 'categories'), array('name', 'label'))
->join(array('g' => 'groups'), 'c.group1 = g.id OR c.group2 = g.id', 'g.label')
->where('g.label = ?', $group)
->where('c.active = 1');
return $dao->fetchAll($select);
You are using a Zend_Db_Table_Select object. Those by default have integrity check enabled and cannot select data that is outside of their table.
You can turn it off by adding -> setIntegrityCheck(false) to the select object before querying with it.
You can read more about it in the manual under Select API -> Advanced usage

Categories