I have two database tables. My comments table looks like this:
comid | comuserid
10 7
20 7
30 9
My replies table looks like this:
repid | repcomid | repfromuser | reptouser
1 10 22 7
2 10 22 7
This is what my index.php page currently looks like:
comid10 (commented by comuserid1)
[repid1] repfromuser22 to comuserid1
comid10 (commented by comuserid1)
[repid2] repfromuser22 to comuserid1
My problem is that my code is ONLY echoing out comments rows that contain repliers, but completely skips over the comments rows that doesn't contain repliers. But I want ALL my comments rows to be echoed out even if they contain no repliers. I also want my repliers grouped together based on the commenter they've commented under. This is the real result I want achieved:
comid10 (commented by comuserid1)
[repid1] repfromuser22 to comuserid1
[repid2] repfromuser22 to comuserid1
comid20 (commented by comuserid1)
comid30 (commented by comuserid2)
How would I achieve that with my current code? Please help:
<?php
$rqid = (int)$_GET['rqid'];
$query = $conn->query("
SELECT comments.*, replies.*, users.username
FROM comments
INNER JOIN replies
ON comments.comid = replies.repcomid
INNER JOIN users
ON comments.comid = users.userid
WHERE comments.comrqid = {$rqid}
");
$comreps = [];
while($row = $query->fetch_object()) {
$comreps[] = $row;
}
?>
<?php foreach($comreps as $comrep): ?>
<div class="rqdivc">
<?php echo $comrep->username; ?>
</div>
<div class="fxrp">
<div>
<?php echo $comrep->repfromuser; ?> -->
<?php echo $comrep->reptouser; ?>
</div>
</div>
<?php endforeach; ?>
Suggested by Strawberry - Use a LEFT JOIN - resolved my issue. Thank you person!
Related
So I have an index.php page that spits out data from two tables on my database. The first table, questions contains one column for my QuestionID and looks like this:
qid
----
1
2
3
The second table called answers contains two columns, one for my AnswersID and the other which links to my QuestionsID on the questions table, and it looks like this:
aid | aqid
----|-----
1 | 3
2 | 1
3 | 1
So on my index.php page, I basically want to echo out every qid row from the questions table and beside it the total number of answers (aid rows from the answers table) corresponding to each QuestionID.
To put simply, the result I want achieved on my index.php page is this:
QuestionID: 1 / Answers: 2
QuestionID: 2 / Answers: 0
QuestionID: 3 / Answers: 1
But based on my current code I am having trouble achieving this result. It keeps echoing out the wrong number of rows for each table. This is the unwanted result I am getting:
QuestionID: 1 / Answers: 3
QuestionID: 2 / Answers: 3
QuestionID: 3 / Answers: 3
So how would I fix this to achieve the correct result? This is my current code:
<?php
$sql = "
SELECT questions.*, GROUP_CONCAT(answers.aqid) AS aqid
FROM questions
LEFT JOIN answers
ON questions.qid=answers.aqid
GROUP BY questions.qid
";
$result = $conn->query($sql);
while($row = $result->fetch_assoc()) {
$qid = $row["qid"];
$aqid = $row["aqid"];
$row_cnt = $result->num_rows;
?>
<div>
QuestionID: <?php echo $qid; ?>
<?php foreach($answers as $answer): ?>
Answers: <?php echo $row_cnt; ?>
<?php endforeach; ?>
</div>
<?php } ?>
Thank you for your help.
group_concat() returns a concatenated string. You might be looking for count().
Also, count() returns a row count.
There doesn't seem to be a need for $row_cnt or the foreach.
Here's an example:
$sql = "
SELECT
q.`qid`,
COUNT(a.`aqid`) AS `answerCount`
FROM `questions` q
LEFT JOIN `answers` a
ON a.`aqid` = q.`qid`
GROUP BY q.`qid`
";
$result = $conn->query($sql);
while($row = $result->fetch_assoc()) {
?>
<div>
QuestionID: <?php echo $row["qid"]; ?>
Answers: <?php echo $row["answerCount"]; ?>
<div>
<?php
}
?>
For information in using codeigniter
I have two tables:
table A has 4 records picture 1
table B has 5 records picutre 2
I want to show that records from 2 tables I have above to my view
but in my view, it just shows 4 records.
4 records from table A
4 records from table B
Even though in table B has 5 records it just shows 4 records
This is my code :
Model
function getAlldata(){
$this->db->select('*');
$this->db->from('data_skm_organisasi');
$this->db- >JOIN('data_skm_kejuaraan','data_skm_kejuaraan.id=data_skm_organisasi.id');
$results = $this->db->get();
return $results->result();
}
controller
public function V_home()
{
$dataSimpanOrganisasi = array();
$dataSimpanOrganisasi ['organisasi']= $this->M_main->getAlldata(); ;
$this->load->view('V_mahasiswa',$dataSimpanOrganisasi);
}
view
<?php foreach ($organisasi as $dataSimpan) { ?>
<div>
<?php echo $dataSimpan->Lembaga; ?>
<?php echo $dataSimpan->tingkatan_O; ?><br><br>
</div>
<?php }
?><br><br>
<?php foreach ($organisasi as $dataSimpan) { ?>
<div>
<?php echo $dataSimpan->jenisKegiatan; ?>
<?php echo $dataSimpan->tingkatan; ?><br><br>
</div>
<?php }
?>
what should I do to my code? is there is any problem in my code?
You are using an normal $db->join command, which is an inner join. This is why you only see the rows of table B, when there is a corredsponding row in table A. In your case, it seems you need an outer join, not an inner join. you can specify it by adding a parameter to your join statement:
$this->db->join('data_skm_kejuaraan', 'data_skm_kejuaraan.id=data_skm_organisasi.id', 'right outer');
I think you used the wrong column to join on the data_skm_kejuaraan table. Try change :
$this->db->JOIN('data_skm_kejuaraan','data_skm_kejuaraan.id=data_skm_organisasi.id');
to
$this->db->JOIN('data_skm_kejuaraan','data_skm_kejuaraan.id_juara=data_skm_organisasi.id');
I have a form which puts together an estimate based on the inputs you fill in and select. One of these inputs is a group of checkboxes that determines what finishes the project receives. They go into the database as an array (name="finishes_id[]"). They are put into a table called finishes_used which looks like the following:
used_id | estimate_id | finish_id
This table links together the finishes table with the estimates table. So for example, if 3 different finishes were chosen for one estimate, it would look like this:
used_id | line_id | estimate_id | finish_id
1 1 1000 2
2 1 1000 6
3 1 1000 7
I am now making an edit page for the estimate and I am having trouble figuring out how to pre-select the finishes checkboxes that were used. It is showing ONLY the checkboxes that were selected. I need the option to check the others as well.
My code for the checkboxes part of my form looks like the following. How can I get the desired results above?
<?php
$getid = $_GET['estimate_id']; // The current estimate number
$getLineid = $_GET['line_id']; // The current line item on the estimate
?>
<label for="finish_id">Finishing</label>
<div class="checkbox_group">
<?php
if ($select = $db -> prepare("SELECT f.finish_id, f.finish_name, u.estimate_id, u.line_id FROM finishes AS f INNER JOIN finishes_used AS u ON u.finish_id = f.finish_id WHERE u.line_id = ? ORDER BY f.finish_name ASC"))
{
$select -> bind_param('s', $getLineID);
$select -> execute();
$select -> bind_result($finish_id, $finish_name, $used_estimate_id, $used_line_id);
while ($select -> fetch())
{
echo '<div class="checkbox">';
echo '<input type="checkbox" name="finish_id[]" id="edit_'.$finish_name.'" value="'.$finish_id.'" ';
echo '/><label for="edit_'.$finish_name.'">'.$finish_name.'</label>';
echo '</div>';
}
$select -> close();
}
?>
</div>
It seems to me you have to use left outer join instead of inner join to achieve this.
Here is a great explanation about joins: What is the difference between "INNER JOIN" and "OUTER JOIN"?
I would like to show the count value for the mysql result in html table.
For an example "district Name1" is the name of "district name" and "count-value1" shows the total post office count in "district name1".
My output must be like this,
------------------------
District | Post Offices
------------------------
Name1 | Count-Value1
Name2 | Count-Value2
Name3 | Count-Value3
Name4 | Count-Value4
... | ...
------------------------
Anyone can please help me to fix this..
This is my PHP code,
<?php
include('config.php');
$data_content= "";
$qry = "SELECT DISTINCT district_N,state_N FROM pincode_data WHERE state_N ='" . mysql_real_escape_string($_GET['st'])."' ORDER BY district_N ASC";
$result = mysql_query($qry);
while($row = mysql_fetch_array($result))
{
$dist_Value = $row['district_N'];
$state_Value = $row['state_N'];
$data_content.= "<tr><td><a href='pincity.php?dist=".$row['district_N']."'> ".$row['district_N']."</a></td><td>Count Value to be Displayed Here</td></tr>";
}
mysql_close();
?>
This is my HTML code,
<html>
<head>
</head>
<body>
<h1>Pincodes in <?php echo $state_Value; ?></h1>
<div>
<table>
<tr><td>District</td><td>Post Offices</td></tr>
<?php echo $data_content; ?>
</table>
</div>
</body>
</html>
SQL has syntax for counting elements of a group. If you want to count all occurrences of each value for X in a table, the general form is select X, count(X) from <table> GROUP BY X. This will group all equal values of X together, and give you a total count of them. For your particular case, try this:
$qry = "SELECT district_N,state_N, COUNT(district_N) cnt
FROM pincode_data WHERE state_N ='" . mysql_real_escape_string($_GET['st'])."'
GROUP BY district_N ORDER BY district_N ASC";
Also, it is good to see that you are escaping the parameters - but mysql_* is deprecated and will be removed in future versions of PHP. You are best off to use either mysqli_* or PDO. In either case, you should also look into prepared statements and parameter binding. It's good for your health.
So I have two tables, article and comments (which has one-to-many relationship (1 article - many comments)). This is how the table is structured:
Articles - id (prikey), title, publicationDate, content
Comments - com_id (prikey), author, comment, id (foreign key)
I used this to query the two tables:
SELECT * FROM articles as a INNER JOIN comments as c ON a.id = c.id
Previously, I was only displaying the articles table using this:
<?php
while($row = mysqli_fetch_array($query)) {
echo "
<div id='article'>
<header>
<hgroup>
<h2>".$row['title']."</h2>
<h4>Posted on ".$row['publicationDate']."</h4>
</hgroup>
</header><p>".$row['content']."</p></div>";
}
?>
This displays all articles (with date, title, content, etc.). Now there are comments. How do I edit the php code (or if my query is incorrect, how to write the query), so that it shows all articles and all comments per article as in:
Article One
-- Comment 1
-- Comment 2, etc.
Article Two
-- Comment 1
-- Comment 2, etc.
An alternative would be to split the query into two.
The first would bring back the articles you want...
SELECT * FROM article;
Once you have those, you can get all the IDs and use something like the following
SELECT * FROM comments WHERE article_id IN (".$list.");
This restricts the MySQL queries to 2 whilst getting all the data you need. After this loop around the article data, and in that loop, loop around the comments data.
This also means that, unlike using GROUP_CONCAT, you will also have author data to use.
It's not a very eloquent solution, but should work.
Query:
SELECT c.author, c.comment,
a.id article_id, a.title, a.publicationDate, a.content
FROM comments c
RIGHT JOIN articles a
ON c.id = a.id
PHP:
<?php
$lastArticleId = 0;
$isNewArticle = false;
while($row = mysqli_fetch_array($query)) {
$isNewArticle = ($lastArticleId != $row['article_id']) ? true : false;
if($isNewArticle) {
$lastArticleId = $row['article_id']; ?>
<div class="article">
<header>
<hgroup>
<h2><?php echo $row['title']; ?></h2>
<h4>Posted on <?php echo $row['publicationDate']; ?></h4>
</hgroup>
</header>
<p><?php echo $row['content']; ?></p>
</div>
<?php
}
if($row['comment'] != '') { ?>
<p><strong><?php echo $row['author']; ?></strong> - <?php echo $row['comment']; ?></p>
<?php
} ?>
<?php
} ?>
Use something like
SELECT a.article
,GROUP_CONCAT(CONCAT('<p>', c.comment, '</p>') SEPARATOR "\n") as comments
FROM
article a
INNER JOIN comment c ON (c.article_id = a.id)
WHERE a.id = '12454';
You may have to fiddle a bit with the separator.
See: http://dev.mysql.com/doc/refman/5.0/en/group-by-functions.html#function_group-concat
Do note however:
The result is truncated to the maximum length that is given by the group_concat_max_len system variable, which has a default value of 1024. The value can be set higher, although the effective maximum length of the return value is constrained by the value of max_allowed_packet. The syntax to change the value of group_concat_max_len at runtime is as follows, where val is an unsigned integer:
SET [GLOBAL | SESSION] group_concat_max_len = val;
See here how to change max_allowed_packet
http://dev.mysql.com/doc/refman/5.5/en/server-system-variables.html#sysvar_max_allowed_packet
Look into MySQL GROUP_CONCAT which will return a comma delimited list of items. You can then explode that for your comments section.
once a person will comment on a article insert article id with that comment and later get them accordingly something like this
once a person will select an article to read send article id in the $_GET to your article page so you can excess the article id.Once a person will comment on that article insert it as follows
$sql = mysql_query("INSERT INTO comments_table (subject,article_id,comments) VALUES ('$subject','$_GET['id']','$comments')");
and later when you pulling them do it the same way as you have the article id in the $_GET
you can access it run a query like this
$fetch = mysql_query("SELECT * FROM comments WHERE article_id = $_GET['id'] ORDER BY id DESC") or die(mysql_error());
Hope this will work