SQL syntax showing date - php

I'm trying to get my article to fetch how many comments it has, and display the number. Here's the code:
<?php
$amount_get = mysql_query("SELECT * FROM comment WHERE id='" . mysql_real_escape_string($_GET['articleid']) . "'");
$comments = mysql_num_rows($amount_get);
$grab = mysql_query("SELECT id, news_title, news_content, news_date, news_author FROM articles ORDER BY id DESC LIMIT 5");
while($row = mysql_fetch_array($grab)){
?>
<div class="pane">
<li>
<h2><?php echo $row['news_title'] ?></h2>
<div class="meta">
<span class="color"> • </span>
<?php echo $row['news_date'] ?>
<span class="color"> • </span>
</div>
Comments: <?php echo $comments ?>
but for some reason, it stays on "0". This is what it looks like:
and my columns are id, articleid,name,comment,date & ip.

Your where clause is looking for id = articleid.
What you want is where articleid = articleid.
$amount_get = mysql_query("SELECT * FROM comment WHERE articleid='" . mysql_real_escape_string($_GET['articleid']) . "'");

It looks like the SQL is faulty. Check your articleid GET variable. Also should it not be doing a different query and mysql_num_rows for each article's comments as each article likely contains different number of comments.
Try this:
SELECT
articles.id, news_title, news_content, news_date, news_author
(SELECT COUNT(*) FROM comment WHERE comment.id=articles.id) as comments
FROM articles
ORDER BY id DESC LIMIT 5
This will get you the first 5 articles and their related comment counts.

You could just use a single query.
$grab = mysql_query(
"SELECT a.id, a.news_title, a.news_content, a.news_date, a.news_author, count(*) as comment_count
FROM articles a
LEFT JOIN comment c ON c.articleid = a.id
ORDER BY a.id DESC LIMIT 5 GROUP BY a.id");
Then instead of
Comments: <?php echo $comments ?>
Do:
Comments: <?php echo $row['comment_count']; ?>
Let me know if the query is working, I'm not sure if the Group by is correctly placed there.

Related

Mysql query returning too many rows

so I have 3 tables all inner joined, I am trying to put discussions with the discussion topic on my main page, with the users name and the latest discussion message on the main page as well.
THE PROBLEM: The query is returning all messages attached to all the discussions.....I just need the last message associated with the discussion returned.
I have been at this all day and cant figure it out. I have tried group by but that just gave me an error on mysqli_fetch_array
Here is my code
$discussionquery = "SELECT discussion_messages.discussion_id, user_profile.first_name, user_profile.last_name, discussion_messages.message_text, case_discussion.discussion_title
FROM `user_profile`
INNER JOIN discussion_messages
ON (user_profile.user_id = discussion_messages.user_id)
INNER JOIN case_discussion
ON (case_discussion.discussion_id = discussion_messages.discussion_id)
WHERE discussion_messages.case_id = '$thecaseid'
ORDER BY discussion_messages.message_id DESC";
$discussionquerydata = mysqli_query($dbc, $discussionquery);
while ($row2 = mysqli_fetch_array($discussionquerydata)) {
$discussion_id = $row2['discussion_id'];
?>
<!-- Begin Recent Discussions -->
<div class="row">
<a href="discussion.php?newfact=$thecaseid'>">
<div class="col-xs-4 col-md-2">
<img src="img/client4.jpg" class="profile_picture img-rounded">
<?php echo '<h6 class="discussionname">' . $row2['first_name'] . ' ' . $row2['last_name'] . '</h6>';?>
</div>
</a>
<div class="col-xs-8 col-md-10 discussion_title">
<?php echo '<h5> '.$row2['discussion_title'].' -'. $row2['message_text'];?></h5>
<h6 class="pull-right">Dec. 25</h6>
</div>
</div>
<?php
};
You need logic to find the last message for each discussion. There is more than one way to write this condition.
The following does it using a not exists clause. This checks that there are no messages with a larger id for the discussion:
SELECT dm.discussion_id, up.first_name, up.last_name, dm.message_text, cd.discussion_title
FROM `user_profile` up INNER JOIN
discussion_messages dm
ON (user_profile.user_id = dm.user_id) INNER JOIN
case_discussion cd
ON (cd.discussion_id = dm.discussion_id)
WHERE dm.case_id = '$thecaseid' and
not exists (select 1
from discussion_messages dm2
where dm2.discussion_id = dm.discussion_id and
dm2.message_id > dm.message_id
)
ORDER BY dm.message_id DESC;
One suggestion, use table aliases. The amount of total code will be smaller and easier to understand. Use the limit clause to return 1 row.
$discussionquery = "
SELECT
m.discussion_id,
u.first_name,
u.last_name,
d.message_text,
c.discussion_title
FROM `user_profile` as u
INNER JOIN discussion_messages as m
ON (u.user_id = m.user_id)
INNER JOIN case_discussion c
ON (m.discussion_id = c.discussion_id)
WHERE
m.case_id = '$thecaseid'
ORDER BY
m.message_id DESC
LIMIT 1";

mysql recieve and compare data from multiple tables

the database tables for debat and comments are the same. it seems that $title and $date isnt working. how can i get the information from both, and order by date?
<?php
$showwall = mysql_query("(SELECT * FROM debat WHERE user='$user') UNION (SELECT * FROM comments WHERE user='$user') ORDER BY date LIMIT 0, 25");
$results = array();
while($wall = mysql_fetch_array($showwall, MYSQL_ASSOC)){ // Line 21
$results[] = $wall;
<li class="comment">
<div class="comment">
<div class="comment-author vcard user frame">
<?php echo "<img src=images/avatar/".$select['avatar']." class=avatar avatar-70 photo height=70 width=70 />"; ?>
</div>
<div class="message">
<span class="reply-link"><?php echo ""; ?> Edit </span>
<div class="info">
<h2><?php echo $wall['title']; ?></h2>
<span class="meta">
<?php
$date->setTimestamp($wall['date']);
echo "Dato: ";
echo $date->format('d-m-Y') . "\n";
echo "Kl: ";
echo $date->format('H:i:s') . "\n";
?>
</span>
</div>
<div class="comment-body ">
<p><?php echo $wall['comment']; ?></p>
</div>
</div>
</div>
</li>
<?php } ?>
I want to add another database to load from, it seems to leave a blank result.
$showwall = #mysql_query("(SELECT * FROM debat WHERE user='$user') UNION (SELECT * FROM comments WHERE user='$user') UNION (SELECT * FROM nyheder WHERE user='$user') ORDER BY date LIMIT 0, 25");
the database contains tables with the same names, but some have more fields than others. So this is isnt the right way to do it?
$showwall = #mysql_query("(SELECT * FROM debat WHERE user='$user') UNION (SELECT * FROM comments WHERE user='$user') UNION (SELECT * FROM nyheder WHERE user='$user') ORDER BY date LIMIT 0, 25")
As mentioned in the comments, the # will suppress error messages; those are there for a reason. You're also not checking the result - adding or die (mysql_error()) would give you the error message from the database.
In this case, the issue is because you're using UNIONs. That will only work if all tables have columns in the same order, and I suspect that that isn't the case. I think you just need a simple JOIN:
SELECT * FROM debat d
INNER JOIN comments c ON d.user=c.user
INNER JOIN nyheder n ON d.user=n.user
WHERE d.user='$user'
One final note - you're using mysql_* functions, which are being removed from PHP. You should look at moving to mysqli_* or PDO instead - they both make it easier for you to write safer code.

post view rank php

Hi everyone i have one question for my dashboard rank panel.
the number of page views I want to sort from smallest to largest.
For example: a total of 100 times a page, but the other page ... 75-74-73-68-45-30 80 times.
I want to get older and smaller than the sequencing of numbers.
My php code is this. post_view is for how many people visit my post .
<?php include("connect.php");
$select_posts = "SELECT * FROM posts LIMIT 0,9";
$run_posts = mysql_query($select_posts);
while($row=mysql_fetch_array($run_posts)){
$post_id = $row['post_id'];
$post_title = $row['post_title'];
$post_date = date('d-m-y');
$post_author = $row['post_author'];
$post_view = $row['post_view'];
?>
<div class="div_name">
<div class="page-id"><?php echo $post_id; ?></div>
<div class="post_title"><?php echo $post_title; ?></div>
<div class="post-view"><?php echo $post_view; ?> </div>
</div>
<?php } ?>
Use SQL's ORDER BY in the query:
SELECT * FROM posts ORDER BY post_view ASC LIMIT 0,9
If this field is not set to a numerical, you can use the following syntax
SELECT * FROM posts ORDER BY cast(post_view as int) ASC LIMIT 0,9

Mysql querys over multiple tables

This code pulls together a list of members then lists all the items they have added in a category and then outputs all this information to a table.
Here's the 3 table layouts:
Members
member_id - fname - lname - etc.
Items
member_id - item_id - etc.
Categories
name - etc.
And the current code which takes FOREVER to load:
<?php $sql="SELECT * FROM members ORDER BY lname, fname ASC";
$result=mysql_query($sql);
while($rows=mysql_fetch_array($result)){ ?>
<? echo('Name'); ?>
<? echo $rows[fname];?> <? echo $rows[lname];?>
<? $sql2="SELECT * FROM leadtypes ORDER BY name ASC";
$result2=mysql_query($sql2);
while($rows2=mysql_fetch_array($result2)){ ?>
<? echo $rows2[name];?>
<? echo(': '); ?>
<? $sql4="SELECT lead_id FROM leads WHERE member_id='$rows[member_id]' AND type='$rows2[name]' ORDER BY name ASC";
$result4=mysql_query($sql4);
$num4 = mysql_num_rows($result4); ?>
<? echo $num4;?>
<? } ?>
<? } ?>`
I know I shouldn't query * but this is a very stripped down piece of code on a test server. I would be grateful If somebody knows a good way of combining all this together to speed up the system.
Try this
$sql = SELECT A.lead_id,B.name,C.fname,C.lname
FROM leads A
JOIN leadtypes B ON A.type = B.name
JOIN members C ON A.member_id = C.member_id
You can echo this as
$rs = mysql_query($sql);
while($rows = mysql_fetch_array($rs)){
echo $row['name'];
echo $row['fname'];
}
Have a look at these links
http://www.w3schools.com/sql/sql_join.asp
http://dev.mysql.com/doc/refman/5.0/en/join.html
Try doing one join instead of multiple queries. For example,
SELECT lt.*, l.lead_id FROM leadtypes lt, leads l WHERE l.member_id=lt.member_id AND l.type=lt.name ORDER BY l.name ASC
If that one query is still slow then it means you need to add indices on your tables.

How to display all comments per article (PHP & SQL)?

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

Categories