join 2 tables and display menu with only group name - php

I have 2 tables:
group
--id
--name
category
--id
--name
--group_id
and the query:
SELECT group.id AS gid, group.name AS gname,
category.id AS cid, category.name AS cname
FROM group join category
on group.id = category.group_id
and result for it is demonstrated as below:
gid--gname--cid--cname
1 ---abc----1----def
1 ---abc----2----ggg
2 ---ccc----3----eee
2 ---ccc----4----fff
I want to show a menu like this:
abc
--def
--ggg
ccc
--eee
--fff
I can't show menu as above if I use that query (infact, I can but it's hard).
What query or a way can help me do this? Thanks so much!

It's a matter of presentation, but you may find it handy to use GROUP_CONCAT() in situation like this to pack categories per group
SELECT g.id gid, g.name gname, GROUP_CONCAT(CONCAT(c.id, '|', c.name) ORDER BY c.id) categories
FROM `group` g JOIN category c
ON g.id = c.group_id
GROUP BY g.id, g.name
Here is SQLFiddle demo
and then easily explode() categories column in php while you iterate over the resultset
Just to give you an idea how php part might look like using PDO
$db = new PDO('mysql:host=localhost;dbname=dbname', 'user', 'password');
$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$db->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);
$sql = "SELECT g.id gid, g.name gname, GROUP_CONCAT(CONCAT(c.id, '|', c.name) ORDER BY c.id) categories
FROM `group` g JOIN category c
ON g.id = c.group_id
GROUP BY g.id, g.name";
$query = $db->prepare($sql);
$query->execute();
$rows = $query->fetchall(PDO::FETCH_ASSOC);
$query = null;
$db = null;
echo '<ul>';
foreach($rows as $row) {
echo '<li>' . $row['gid'] . '-' . $row['gname'];
$categories = explode(',', $row['categories']);
echo '<ul>';
foreach($categories as $category) {
list($cid, $cname) = explode('|', $category);
echo '<li>' . $cid . '-' .$cname . '</li>';
}
echo '</ul></li>';
}
echo '</ul>';
Output:
1-abc1-def2-ggg2-ccc3-eee4-fff

basically you have to loop for each group and printing all category belong to that group.
in php u can do this:
while( $group = mysql_fetch_array( mysql_query("SELECT id, name FROM group") ) ){
echo $group[1];
while( $category = mysql_fetch_array( mysql_query("SELECT id, name from category where group_id =" . $group[0] ) ) ){
echo $category[1];
}
}

Try this:
$arr = array(
array('gid'=>1, 'gname'=>'abc', 'cid'=>1, 'cname'=>'def'),
array('gid'=>1, 'gname'=>'abc', 'cid'=>2, 'cname'=>'ggg'),
array('gid'=>2, 'gname'=>'ccc', 'cid'=>3, 'cname'=>'eee'),
array('gid'=>2, 'gname'=>'ccc', 'cid'=>4, 'cname'=>'fff'),
);
$res = array();
foreach($arr as $ar){
if(empty($res[$ar['gid']])){
$res[$ar['gid']] = array(
'gid'=>$ar['gid'],
'gname'=>$ar['gname'],
);
}
$res[$ar['gid']]['category'][] = array('cid'=>$ar['cid'],'cname'=>$ar['cname']);
}
print_r($res);

Related

How to select comments with child comments from MySQL?

I have two tables:
'comments'
| id | content | user_id | article_id | parent_id |
'users'
| id | name | photo |
And my queries are:
<?php
$query = mysql_query("SELECT comments.id, comments.content, users.name,
users.photo FROM comments, users WHERE comments.article_id = '".$get_id."'
AND comments.parent_id = 0 AND comments.user_id = users.id");
while($res = mysql_fetch_assoc($query))
{
$id = $res['id'];
$content = $res['content'];
$name = $res['name'];
$photo = $res['photo'];
echo $photo;
echo $name;
echo $content;
$query2 = mysql_query("SELECT comments.id, comments.content, users.name,
users.photo FROM comments, users WHERE comments.article_id = '".$get_id."'
AND comments.parent_id = '".$id."' AND comments.user_id = users.id");
while($res2 = mysql_fetch_assoc($query2))
{
$id2 = $res2['id'];
$content2 = $res2['content'];
$name2 = $res2['name'];
$photo2 = $res2['photo'];
echo $photo2;
echo $name2;
echo $content2;
}
}
?>
It doesn't work properly. It shows 1 parent and 1 child comment in each nest although there are several child comments.
How can I fix and minimize it? Can it be done by using only one query?
Thank you!
JOIN the table on itself.
Change your query to:
SELECT comments.id, comments.content, users.name,
users.photo FROM comments JOIN users ON comments.user_id = users.id JOIN
comments c ON comments.id =
c.parent_id WHERE
comments.article_id = '".$get_id."'
AND comments.parent_id = '".$id."'
You don't need the second query, here's the full code:
<?php
$query = mysql_query("SELECT comments.id, comments.content, users.name,
users.photo FROM comments JOIN users ON comments.user_id = users.id JOIN
comments c ON comments.id =
c.parent_id WHERE
comments.article_id = '".$get_id."'");
while($res = mysql_fetch_assoc($query))
{
$id = $res['id'];
$content = $res['content'];
$name = $res['name'];
$photo = $res['photo'];
echo $photo;
echo $name;
echo $content;
}
?>
Just use a JOIN to fetch the comments and with all the children.
SELECT users.id userID, users.name, users.photo , childrenComments.*,
parentComments.id cpId, parentComments.content cpContent,
parentComments.user_id cpUser_id,parentComments.article_id cpArticleId
FROM users JOIN (SELECT * FROM Comment WHERE id=0) parentComments
ON users.id=parentComments.user_id LEFT JOIN Comment childrenComments
ON parentComments.id=childrenComments.parent_id;
Then you can the loop through the result to print it appropriately. This would be better as you would have to run just a single query.

Binding multiple arrays in pdo

There are 3 different filters: books, authors and stores (select lists), and I may use their all together at once or only one or two of them, so I use UNION to get together all queries
require('database.php');
if(isset($_POST['books'])){
$books_ids = $_POST["books"];
}
if(isset($_POST['authors'])){
$authors_ids = $_POST["authors"];
}
if(isset($_POST['stores'])){
$stores_ids = $_POST["stores"];
}
$query = "";
if( !empty( $books_ids ))
{
$books_ids_in = implode(',', array_fill(0, count($books_ids), '?'));
$query .= "SELECT
b.id,
b.`name`,
b.`year`,
GROUP_CONCAT(DISTINCT a.`name`) AS author_names,
GROUP_CONCAT(DISTINCT s.`name`) AS store_names,
'book' as param
FROM
books AS b
LEFT JOIN books_authors AS b_a ON b.id = b_a.book_id
LEFT JOIN authors AS a ON a.id = b_a.author_id
LEFT JOIN books_stores AS b_s ON b.id = b_s.book_id
LEFT JOIN stores AS s ON s.id = b_s.store_id
WHERE
b.id IN (". $books_ids_in .")
GROUP BY b.id
ORDER BY b.id";
}
if( !empty( $authors_ids ) )
{
$authors_ids_in = implode(',', array_fill(0, count($authors_ids), '?'));
if (!empty($query)) {
$query .= " UNION ";
}
$query .= "SELECT
b.id,
b.`name`,
b.`year`,
GROUP_CONCAT(DISTINCT a.`name`) AS author_names,
GROUP_CONCAT(DISTINCT s.`name`) AS store_names,
'author' as param
FROM
books AS b
LEFT JOIN books_authors AS b_a ON b.id = b_a.book_id
LEFT JOIN authors AS a ON a.id = b_a.author_id
LEFT JOIN books_stores AS b_s ON b.id = b_s.book_id
LEFT JOIN stores AS s ON s.id = b_s.store_id
WHERE
b.id IN (
SELECT DISTINCT book_id FROM books_authors WHERE author_id IN (". $authors_ids_in .")
)
GROUP BY b.id
ORDER BY b.id";
}
if( !empty( $stores_ids ) )
{
$stores_ids_in = implode(',', array_fill(0, count($stores_ids), '?'));
if (!empty($query)) {
$query .= " UNION ";
}
$query .= "SELECT
b.id,
b.`name`,
b.`year`,
GROUP_CONCAT(DISTINCT a.`name`) AS author_names,
GROUP_CONCAT(DISTINCT s.`name`) AS store_names,
'store' as param
FROM
books AS b
LEFT JOIN books_authors AS b_a ON b.id = b_a.book_id
LEFT JOIN authors AS a ON a.id = b_a.author_id
LEFT JOIN books_stores AS b_s ON b.id = b_s.book_id
LEFT JOIN stores AS s ON s.id = b_s.store_id
WHERE
b.id IN (
SELECT DISTINCT book_id FROM books_stores WHERE store_id IN (". $stores_ids_in .")
)
GROUP BY b.id
ORDER BY b.id";
}
if( !empty( $query )) {
$stmt = $conn->prepare($query);
if( !empty( $books_ids ))
{
foreach ($books_ids as $k => $id) {
$stmt->bindValue(($k+1), $id);
}
}
if( !empty( $authors_ids ))
{
foreach ($authors_ids as $k => $id) {
$stmt->bindValue(($k+1), $id);
}
}
if( !empty( $stores_ids ))
{
foreach ($stores_ids as $k => $id) {
$stmt->bindValue(($k+1), $id);
}
}
$stmt->execute();
$results = $stmt->fetchAll();
echo json_encode($results);
}
$conn = null;
code works just fine when I use only one filter, but when I try to use 2 or more, I get error
Fatal error: Uncaught exception 'PDOException' with message 'SQLSTATE[HY093]: Invalid parameter number: number of bound variables does not match number of tokens' in C:\xampp\htdocs\bookstore\filter.php:123 Stack trace: #0 C:\xampp\htdocs\bookstore\filter.php(123): PDOStatement->execute() #1 {main} thrown in C:\xampp\htdocs\bookstore\filter.php on line 123
I guess, something's wrong with bindValue using but I don't know how to fix that?
UPD
var_dump($query) (3 books and 2 authors chosen)
string(1097) "SELECT b.id, b.name, b.year, GROUP_CONCAT(DISTINCT a.name) AS author_names, GROUP_CONCAT(DISTINCT s.name) AS store_names, 'book' as param FROM books AS b LEFT JOIN books_authors AS b_a ON b.id = b_a.book_id LEFT JOIN authors AS a ON a.id = b_a.author_id LEFT JOIN books_stores AS b_s ON b.id = b_s.book_id LEFT JOIN stores AS s ON s.id = b_s.store_id WHERE b.id IN (?,?,?) GROUP BY b.id ORDER BY b.id UNION SELECT b.id, b.name, b.year, GROUP_CONCAT(DISTINCT a.name) AS author_names, GROUP_CONCAT(DISTINCT s.name) AS store_names, 'author' as param FROM books AS b LEFT JOIN books_authors AS b_a ON b.id = b_a.book_id LEFT JOIN authors AS a ON a.id = b_a.author_id LEFT JOIN books_stores AS b_s ON b.id = b_s.book_id LEFT JOIN stores AS s ON s.id = b_s.store_id WHERE b.id IN ( SELECT DISTINCT book_id FROM books_authors WHERE author_id IN (?,?) ) GROUP BY b.id ORDER BY b.id" 01201
There are problems with your code for building a dynamic query.
When building a dynamic query you need to separate those parts of the query that are static from those that are dynamic.
You can see that the following code is static.
$query = "SELECT
b.id,
b.`name`,
b.`year`,
GROUP_CONCAT(DISTINCT a.`name`) AS author_names,
GROUP_CONCAT(DISTINCT s.`name`) AS store_names,
'book' as param
FROM
books AS b
LEFT JOIN books_authors AS b_a ON b.id = b_a.book_id
LEFT JOIN authors AS a ON a.id = b_a.author_id
LEFT JOIN books_stores AS b_s ON b.id = b_s.book_id
LEFT JOIN stores AS s ON s.id = b_s.store_id ";
And also
" GROUP BY b.id
ORDER BY b.id";
The rest of the code is dynamic.
When filtering records the WHERE clause is used and the AND & OR operators are used to filter records based on more than one condition.
The AND operator displays a record if both the first condition AND the second condition are true.
The OR operator displays a record if either the first condition OR the second condition is true.
so for the first condition WHERE is used but after that AND or OR must be used(using OR in your example)
// Static code
sql = "SELECT * FROM `table`"
// Set initial condition to WHERE
clause = "WHERE";
if( !empty( filter )){
Add clause to sql
Add condition to sql
change clause to OR or AND as required
}
Repeat for each filter
Note the filter is not changed until a filter is not empty and remains changed once changed.
The remaining static code is added after all the filters have been handled
To allow different filters to be applied you can use a flag.
$flag = 0;
if(isset($_POST['books'])){
$books_ids = $_POST["books"];
$flag += 1;
}
if(isset($_POST['authors'])){
$authors_ids = $_POST["authors"];
$flag += 10;
}
if(isset($_POST['stores'])){
$stores_ids = $_POST["stores"];
$flag += 100;
}
Use "lazy" binding when possible - passing data into execute will dramatically shorten your code.
See PDO info
You require to merge array to perform this. Using switch statement with the flag you merge the arrays required.
switch ($flag) {
case 1:
$param_array = $books_ids;
break;
case 10:
$param_array = $authors_ids;
break;
case 100:
$param_array = $stores_ids;
break;
case 11://books & authors
$param_array = array_merge($books_ids, $authors_ids);
break;
case 101://books & stores
$param_array = array_merge($books_ids, $stores_ids);
break;
case 110://authors & stores
$param_array = array_merge($authors_ids, $stores_ids);
break;
case 111://books & authors & stores
$param_array = array_merge(array_merge($books_ids,$authors_ids),$stores_ids);
break;
}
if( !empty( $query )) {
$stmt = $conn->prepare($query);
$stmt->execute($param_array);
$results = $stmt->fetchAll();
echo json_encode($results);
}
The following code uses the above points. I have echoed some lines to indicate results which can be removed once testing is done.Also some code has been commented out for testing.
//Set flag
$flag = 0;
if(isset($_POST['books'])){
$books_ids = $_POST["books"];
$flag += 1;
}
if(isset($_POST['authors'])){
$authors_ids = $_POST["authors"];
$flag += 10;
}
if(isset($_POST['stores'])){
$stores_ids = $_POST["stores"];
$flag += 100;
}
echo $flag. " <BR>";//Remove after testing
//Basic SQL statement
$query = "SELECT
b.id,
b.`name`,
b.`year`,
GROUP_CONCAT(DISTINCT a.`name`) AS author_names,
GROUP_CONCAT(DISTINCT s.`name`) AS store_names,
'book' as param
FROM
books AS b
LEFT JOIN books_authors AS b_a ON b.id = b_a.book_id
LEFT JOIN authors AS a ON a.id = b_a.author_id
LEFT JOIN books_stores AS b_s ON b.id = b_s.book_id
LEFT JOIN stores AS s ON s.id = b_s.store_id ";
// Set initial condition to WHERE
$clause = "WHERE";
if( !empty( $books_ids ))
{
$books_ids_in = implode(',', array_fill(0, count($books_ids), '?'));
$query .= $clause;
$query .= " b.id IN (". $books_ids_in .")";
// Set condition to OR for additional condition
$clause = " OR ";
}
if( !empty( $authors_ids ) )
{
$authors_ids_in = implode(',', array_fill(0, count($authors_ids), '?'));
/* This part commented out as I don't see relevance
if (!empty($query)) {
$query .= " UNION ";
}
*/
$query .= $clause;
$query .= " b.id IN (
SELECT DISTINCT book_id FROM books_authors WHERE author_id IN (". $authors_ids_in .")
)";
// Set condition to OR for additional condition
$clause = " OR ";
}
if( !empty( $stores_ids ) )
{
$stores_ids_in = implode(',', array_fill(0, count($stores_ids), '?'));
/* if (!empty($query)) {
$query .= " UNION ";
}
*/
$query .= $clause;
$query .= " b.id IN (
SELECT DISTINCT book_id FROM books_stores WHERE store_id IN (". $stores_ids_in .")
)";
$clause = " OR ";
}
//Add GROUP & ORDER
$query .= " GROUP BY b.id
ORDER BY b.id";
echo $query; //Remove after testing
//building $param_array
switch ($flag) {
case 1:
$param_array = $books_ids;
break;
case 10:
$param_array = $authors_ids;
break;
case 100:
$param_array = $stores_ids;
break;
case 11://books & authors
$param_array = array_merge($books_ids, $authors_ids);
break;
case 101://books & stores
$param_array = array_merge($books_ids, $stores_ids);
break;
case 110://authors & stores
$param_array = array_merge($authors_ids, $stores_ids);
break;
case 111://books & authors & stores
$param_array = array_merge(array_merge($books_ids,$authors_ids),$stores_ids);
break;
}
echo "<br>";
print_r($param_array);// remove after testing
/*
if( !empty( $query )) {
$stmt = $conn->prepare($query);
$stmt->execute($param_array);
$results = $stmt->fetchAll();
echo json_encode($results);
}
$conn = null;
Don't use same $k; use a variable and increment it with each bind; See below
$bindingIndex = 0;
if( !empty( $books_ids ))
{
foreach ($books_ids as $k => $id) {
$stmt->bindValue((++$bindingIndex), $id);
}
}
if( !empty( $authors_ids ))
{
foreach ($authors_ids as $k => $id) {
$stmt->bindValue((++$bindingIndex), $id);
}
}
if( !empty( $stores_ids ))
{
foreach ($stores_ids as $k => $id) {
$stmt->bindValue((++$bindingIndex), $id);
}
}

Select from two tables where company_id=$company->id

hello I have this variable $company->id
and I have function like this
<?php
function GetEmploees(){
$db = JFactory::getDBO();
$query = 'SELECT * FROM #__jbusinessdirectory_attribute_options AS c JOIN #__jbusinessdirectory_company_attributes AS cp
on c.id = cp.option_id';
$db->setQuery($query);
if( $rows = $db->loadObjectList() ) {
foreach( $rows as $row ){
echo $row->name;
}
}
}
echo GetEmploees($company->id);
?>
I want select $row->name as $company->id
how can I insert code WHERE company_id = '.$company->id.' in query?
company_id is in table #__jbusinessdirectory_company_attributes
Try
$sql = "SELECT * FROM #__jbusinessdirectory_attribute_options AS c INNER JOIN #__jbusinessdirectory_company_attributes AS cp (on c.id = cp.option_id) WHERE c.company_id = '.$company->id.'";
Should do the trick

PHP / MySQL relation between 2 tables

I am using the following tables:
artists
related_artists
The idea is when I enter an artist's page with an artist_id I can use that id to load related artists. The following code works, but how do I put it in a single query? I can't figure it out.
To connect related_artists with artists I created the following code:
$sql = "SELECT related_artist_id FROM related_artists WHERE artist_id = 1";
$res = mysqli_query($db, $sql);
if (!$res) {
echo "Er is een fout opgetreden.";
exit;
} else {
while ($row = mysqli_fetch_array($res)) {
$query = 'SELECT * FROM artists WHERE artist_id = '.$row["related_artist_id"];
print_r($query."<br />\n");
$result = mysqli_query($db, $query);
if ($result) {
while ($test = mysqli_fetch_array($result)) {
echo $test["lastName"]."<br />\n";
}
} else {
echo "It doesn't work";
exit;
}
}
}
You can just try :
select *
from artists
where artist_id in (
select related_artist_id
from related_artists
WHERE artist_id = 1
);
You can use a LEFT JOIN, try this:
SELECT b.*
FROM related_artist a
LEFT JOIN artists b
USING(artist_id)
WHERE a.artist_id = 1
Should return * from artists, where I aliased artists as b and related_artist as a.
Didn't test, does it work for you / return the expected result?
SELECT * FROM artists where artists.arist_id = 1
INNER JOIN related_artist ON related_artist.artist_id = artists.artist_id
This provides a join on the artist_id columns of both tables, having artist_id = 1. I'm not sure if you need an Inner or a Left join

Template system while in a while

I am trying to make put comments below the answers that I loop (just like answers on stackoverflow) But I can't find out how to put the right comment below the right answer. I am using the template system with this.
With what I currently have it only shows the comments of the query with the last $row['id']
PHP Code:
<?php
//Query setup for answers
$answerquery = "SELECT a.id, a.post_id, a.username, a.date, a.text FROM answers_tbl AS a, posts_tbl AS p WHERE a.post_id = p.id";
$result = $mysqli->query($answerquery);
//Replace answers
$layout_a = file_get_contents("tpl/question_answer_layout.html");
$search_a = array("%username%", "%date_a%", "%text_a%");
$answer_r = NULL;
while($row = $result->fetch_array()){
$replace_a = array($row['username'], $row['date'], $row['text']);
$answer_r .= str_replace($search_a, $replace_a, $layout_a);
//Query setup for comments of the question
$commentquery = "SELECT c.username, c.comment
FROM answer_comments_tbl AS c
INNER JOIN answers_tbl AS a ON a.id = c.answer_id
WHERE answer_id =".$row['id'];
$result2 = $mysqli->query($commentquery);
//Replace comments
$layout_c = file_get_contents("tpl/question_comment_layout.html");
$search_c = array("%comment_c%", "%username_c%");
$answer_c = NULL;
while($row2 = $result2->fetch_assoc()){
$replace_c = array($row2['comment'], $row2['username']);
$answer_c = str_replace($search_c, $replace_c, $layout_c);
$answer_r = str_replace("%answer_comment%", $answer_c, $answer_r);
}
}
$template = str_replace("%answer_post%", $answer_r, $template);
?>
question_answer_layout.html:
<div id="AnswerCarTop">
</div><!--Question-->
<div id="QuestionBottom">
<div id="QuestionTitle">%username%</div><!--QuestionTitle-->
<div id="Paragraph">%text_a%</div><!--Paragraph-->
%answer_comment%
question_comment_layout.html:
<div id="CommentPlaced">
<div id="Paragraph1">%comment% - <span class="bold">%username%</span></div>
<!--Paragraph--></div>
There are a few problems with your code that prevent it from working correctly.
First of all, the query to retrieve the comments needs to do a join between the two tables you are using, otherwise it will perform a cartesian product of the two tables (every answer is joined to every comment and then filtered by where). You should rewrite it as:
SELECT c.username, c.comment
FROM answer_comments_tbl AS c
INNER JOIN answers_tbl AS a ON a.id = c.answer_id
WHERE answer_id = $row['id']
Of course, using prepared statements is another matter entirely.
The second problem is the order in which you're doing your replacements. The basic structure (in pseudocode) should be:
for each answer {
for each comment {
comment = apply the comment template
comments_string += comment
}
apply the posts template, using the previously calculated comments_string
}
The third problem is the general approach of performing a separate query for every answer. You can solve this problem with just 2 queries (or even a single one, but then it's a more delicate matter which will certainly derive into its own discussion). The better approach would be to get all the answers for the post, then get all the comments that are related to that post. After that you can group up the comments to know where each one comes from.
Here is the fully edited code. I didn't add prepared statements because it's beyond the scope of this answer, but you should definitely use them.
<?php
//Query setup for answers
$answerquery = "
SELECT a.id, a.post_id, a.username, a.date, a.text
FROM answers_tbl AS a
INNER JOIN posts_tbl AS p ON a.post_id = p.id
WHERE p.id = " . (int) $post_id;
$answerResult = $mysqli->query( $answerquery );
// Query setup for comments
$commentsQuery = "
SELECT c.username, c.comment, c.answer_id
FROM answer_comments_tbl AS c
INNER JOIN answers_tbl AS a ON a.id = c.answer_id
WHERE a.post_id = " . (int) $post_id;
$commentsResult = $mysqli->query( $commentsQuery );
// Group the comments by answer
$groupedComments = array();
while( $row = $mysqli->fetch_assoc( $commentsResult ) ) {
if( ! isset( $groupedComments[ $row['answer_id'] ] ) ) {
$groupedComments[ $row['answer_id'] ] = array();
}
$groupedComments[ $row['answer_id'] ][] = $row;
}
// Loading the template files only once
$layout_a = file_get_contents( 'tpl/question_answer_layout.html' );
$search_a = array( '%username%', '%date_a%', '%text_a%');
$layout_c = file_get_contents( 'tpl/question_comment_layout.html' );
$search_c = array( '%comment%', '%username%');
// This will hold the string with all the answers and their comments
$answers = null;
while( $row = $answerResult->fetch_assoc() ) {
// This will hold all the comments for the current answer
$answer_comment = null;
foreach( $groupedComments[ $row['id'] ] as $comment ) {
// Apply the comment layout
$replace_c = array( $comment['comment'], $comment['username'] );
$answer_comment .= str_replace( $search_c, $replace_c, $layout_c );
}
// Apply the answer layout
$replace_a = array( $row['username'], $row['date'], $row['text'], $answer_comment );
$answers .= str_replace( $search_a, $replace_a, $layout_a );
}
// Add all the answers and the comments to the main template
$template = str_replace( '%answer_post%', $answers, $template );
This worked for me and solved my question:
<?php
//Query setup for answers
$answerquery = "SELECT a.id, a.post_id, a.username, a.date, a.text FROM answers_tbl AS a, posts_tbl AS p WHERE a.post_id = p.id";
$result = $mysqli->query($answerquery);
//Replace answers
$layout_a = file_get_contents("tpl/question_answer_layout.html");
$search_a = array("%username%", "%date_a%", "%text_a%");
$answer_r = NULL;
while($row = $result->fetch_array()){
$replace_a = array($row['username'], $row['date'], $row['text']);
$answer_r .= str_replace($search_a, $replace_a, $layout_a);
//Query setup for comments of the question
$commentquery = "SELECT c.username, c.comment
FROM answer_comments_tbl AS c
INNER JOIN answers_tbl AS a ON a.id = c.answer_id
WHERE answer_id =".$row['id'];
$result2 = $mysqli->query($commentquery);
//Replace comments
$layout_c = file_get_contents("tpl/question_comment_layout.html");
$search_c = array("%comment%", "%username%");
$answer_c = NULL;
while($row2 = $result2->fetch_assoc()){
$replace_c = array($row2['comment'], $row2['username']);
$answer_c .= str_replace($search_c, $replace_c, $layout_c);
}
$answer_r = str_replace("%answer_comment%", $answer_c, $answer_r);
}
$template = str_replace("%answer_post%", $answer_r, $template);
?>

Categories