Get number of posts in a topic PHP - php

How do I get to display the number of posts on a topic like a forum. I used this... (how very noobish):
function numberofposts($n)
{
$sql = "SELECT * FROM posts
WHERE topic_id = '" . $n . "'";
$result = mysql_query($sql) or die(mysql_error());
$count = mysql_num_rows($result);
echo number_format($count);
}
The while loop of listing topics:
<?php
$sql = "SELECT * FROM topics ORDER BY topic_id ASC LIMIT $start, $limit";
$result = mysql_query($sql) or die(mysql_error());
while($row = mysql_fetch_array($result))
{
?>
<div class="topics">
<div class="topic-name">
<p><?php echo $row['topic_title']; ?></p>
</div>
<div class="topic-posts">
<p><?php echo numberofposts($row['topic_id']); ?></p>
</div>
</div>
<?php
}
?>
Although it is a bad method of doing this... All I need is to know what would be the best method, don't just point me out to a website, do it here, because I'm trying to learn much. Okay? :D
Thanks.
EDIT:
SQL:
Posts table:
CREATE TABLE `posts` (
`post_id` mediumint(8) NOT NULL AUTO_INCREMENT,
`topic_id` mediumint(8) NOT NULL,
`forum_id` mediumint(8) NOT NULL,
`user_id` mediumint(8) NOT NULL,
`post_time` varchar(100) NOT NULL,
`post_timestamp` mediumint(20) NOT NULL,
`post_ip` varchar(20) NOT NULL,
`post_reported` tinyint(1) NOT NULL,
`post_reportdesc` text NOT NULL,
PRIMARY KEY (`post_id`)
) ENGINE=MyISAM DEFAULT CHARSET=latin1 AUTO_INCREMENT=2 ;
--
-- Dumping data for table `posts`
--
INSERT INTO `posts` VALUES(1, 1, 0, 1, '15th Junenee', 0, '', 0, '');
Topics table:
CREATE TABLE `topics` (
`topic_id` mediumint(8) NOT NULL AUTO_INCREMENT,
`section_name` varchar(25) NOT NULL,
`topic_title` varchar(120) NOT NULL,
`topic_description` char(120) NOT NULL,
`user_id` mediumint(8) NOT NULL,
`topic_time` varchar(100) NOT NULL,
`topic_views` varchar(1000) NOT NULL,
`topic_up` mediumint(11) NOT NULL,
`topic_down` mediumint(11) NOT NULL,
`topic_status` tinyint(1) NOT NULL,
PRIMARY KEY (`topic_id`)
) ENGINE=MyISAM DEFAULT CHARSET=latin1 AUTO_INCREMENT=1 ;
This should help you understand a bit more.

You can use:
"SELECT COUNT(topic_id) FROM posts WHERE topic_id = '?'"
The ? is a place-holder. If you use mysql, you should use mysql_real_escape_string:
$sql = "SELECT COUNT(topic_id)
WHERE topic_id = '" . mysql_real_escape_string($n) . "'";
If you use mysql_fetch_array, $row[0] will be the count. You can name it but it's not necessary.
A better option is some kind of prepared statements, such as PDOStatement or mysqli_stmt. This helps prevent SQL injection.

When you're listing topics, you should include the post count in a join:
SELECT t.*, COUNT(p.post_id) AS post_count
FROM topic t LEFT JOIN posts p ON p.topic = t.topic_id
GROUP BY t.topic_id
Didn't study your schema too much, but you get the point.

You could use this SQL query instead if you only want the number of records:
SELECT COUNT(topic_id) AS 'count' WHERE topic_id = '123'
Then after you do:
$result = mysql_query($sql);
if ($result !== false)
{
$row = mysql_fetch_assoc($result);
if ($row !== false)
echo('Number of rows = ' . $row['count']);
}

SELECT topic_title, COUNT(*) AS toipic_count
FROM topics
GROUP BY topic_id
ORDER BY topic_id ASC
Then you will not need any more mysql-querys, just use:
$row['topic_count']

Related

How to show reviews per restaurant in php with mysql?

I am trying to show the amount of reviews for each restaurant.
I made 2 tables containing my data.
CREATE TABLE `restaurants` (
`id` int(4) NOT NULL AUTO_INCREMENT,
`name` varchar(200) NOT NULL,
`city` varchar(200) NOT NULL,
`country` varchar(200) NOT NULL,
`score` int(1) NOT NULL DEFAULT '0',
`reviews` int(1) NOT NULL DEFAULT '0',
`slug` varchar(200) NOT NULL DEFAULT 'slug-test',
`approved` int(1) NOT NULL DEFAULT '0',
`description` text NOT NULL,
`review` int(11) DEFAULT '0',
`created_date` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
`updated_date` timestamp NOT NULL DEFAULT '0000-00-00 00:00:00',
`img_url` varchar(255) NOT NULL,
`category` varchar(255) NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=65 DEFAULT CHARSET=latin1
CREATE TABLE `reviews` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`restaurant_id` int(11) NOT NULL,
`review_text` text NOT NULL,
`score` int(11) NOT NULL,
PRIMARY KEY (`id`),
KEY `restaurant_id` (`restaurant_id`),
CONSTRAINT `reviews_ibfk_1` FOREIGN KEY (`restaurant_id`) REFERENCES `restaurants` (`id`) ON DELETE NO ACTION ON UPDATE NO ACTION
) ENGINE=InnoDB AUTO_INCREMENT=2 DEFAULT CHARSET=latin1
I am already showing my restaurants in a list.
$query = "SELECT * FROM restaurants WHERE approved = 1 ORDER BY created_date DESC";
$result = $mysqli->query($query);
while($row = $result->fetch_array()) {
**HTML WITH MY VARIABLES**
}
This is how u currently show my reviews (hardcoded result in my restaurants table.
if ($reviews <= "0") {
echo "<a href='#' title='Write reviews'><p class='purple-def-color fz-12 mb-0'>write a review</p></a>";
} else if ($reviews > "1") {
echo "<p class='purple-def-color mb-0'>". $row['reviews'] ." reviews</p>";
} else {
echo "<p class='purple-def-color mb-0'>" . $row['reviews'] . " review</p>";
}
I tried to use a JOIN query but was not successful to show the amount of reviews in any way.
Based on your table structure, you can get a review count for each restaurant by joining the reviews table, selecting the COUNT of reviews, and grouping by restaurant ID.
Grouping by restaurant allows you to get an aggregate (e.g. count) of the joined review records for each restaurant.
SELECT
rs.*,
COUNT(rv.`id`) as `reviewCount`
FROM `restaurants` rs
LEFT JOIN `reviews` rv
ON (rv.`restaurant_id` = rs.`id`)
WHERE rs.`approved` = 1
GROUP BY rs.`id`
ORDER BY rs.`created_date` DESC;
Then, when you fetch the rows in PHP, you can reference each row's review count:
echo $row['reviewCount'];
To further demonstrate aggregate functions, here's an example of how to select the average, minimum, and maximum review score for each restaurant:
SELECT
rs.*,
COUNT(rv.`id`) as `reviewCount`,
AVG(rv.`score`) as `reviewAverageScore`,
MIN(rv.`score`) as `reviewMinScore`,
MAX(rv.`score`) as `reviewMaxScore`
FROM `restaurants` rs
LEFT JOIN `reviews` rv
ON (rv.`restaurant_id` = rs.`id`)
WHERE rs.`approved` = 1
GROUP BY rs.`id`
ORDER BY rs.`created_date` DESC;
Try a left join:
$query = 'SELECT * FROM restaurants LEFT JOIN reviews on reviews.restaurant_id = restaurants.id'
A left join returns all records from the left table (restaurants), and the matched records from the right table (reviews)

add friend system in php

I am trying to build a friend system in php I have the tables, database and the logic in place. I am having trouble getting the friend request receiver's id.
I have registeredusers friends updates table. The registeredusers table looks like this,
CREATE TABLE `registeredusers` (
`id` int(11) NOT NULL,
`FirstName` varchar(50) NOT NULL,
`LastName` varchar(50) NOT NULL,
`UserName` varchar(50) NOT NULL,
`Email` varchar(50) NOT NULL,
`Password` varchar(255) NOT NULL,
`ResetPassword` int(7) DEFAULT NULL,
`friends` int(255) DEFAULT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
friends
CREATE TABLE `friends` (
`friend_one` int(11) NOT NULL,
`friend_two` int(11) NOT NULL,
`status` enum('0','1','2') DEFAULT '0'
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
The requester's ID would be INSERTED into friend_two and receiver's ID would get into friend_one. here's my code
<?php
include 'dbh.php';
$sql = "SELECT * FROM registeredusers";
$result = mysqli_query($connection,$sql);
$row = mysqli_fetch_assoc($result);
$username = $row['UserName'];
$requesterU = $_GET['user'];
echo "the requester is ".$requesterU;
while($row=mysqli_fetch_array($result)){
$id = $row[0];
$username = $row[1];
echo "
<form action='list of users.php'>
$id $username<input type='submit' value='send request' name='friendsbanalo'></input></form>";
}
$sql = "SELECT * FROM registeredusers WHERE UserName = '$requesterU'";
$result = mysqli_query($connection,$sql);
$row = mysqli_fetch_assoc($result);
$requester_id = $row['id'];
echo "requester's id ".$requester_id;
if(isset($_POST['friendsbanalo'])){
$sql = "INSERT INTO friends (friend_one,friend_two) VALUES('$requester_id','$reciver_userid')";
$result = mysqli_query($connection, $sql);
}else{
echo "error";
}
?>
I am not able to get the receiver's ID, can anyone tell me how can I get receiver's ID? I tried searching for the solution and the answers were too complicated for me to understand. I tried (on a separate file) INNER JOIN but I couldn't get it to work.

How to join two tables and return result in php

I have two tables namely: users and messages
I want to JOIN messages table with users table and select users information from users table where the id in users table has NO row in messages table checking with the hash column.
Please Note: user_two column in messages table is the ids from users table
I tried but it return no result.
Please help:
<?php
//Get the friend a user wants to send message
if(isset($_POST['recipname']) && !empty($_POST['recipname'])){
$recipname = mysqli_real_escape_string($dbc_conn,htmlentities(trim($_POST['recipname'])));
$message_group_tatable = "messages";
$sql = "
SELECT users.id, users.username,users.FirstName ,
users.LastName , users.avatar ,
users.cell_group
FROM users
INNER JOIN $message_group_tatable
ON $table_name.id=$message_group_tatable.user_two
WHERE $message_group_tatable.hash = NULL
AND users.id != $message_group_tatable.user_two
AND users.username
LIKE '%$recipname%'
LIMIT 6
";
$query = mysqli_query($dbc_conn,$sql);
//die(mysqli_error($dbc_conn));
if(mysqli_num_rows($query) > 0){
while($row = mysqli_fetch_array($query)){
$name = ucfirst($row['FirstName'])." ".ucfirst($row['LastName']);
$user_id = $row['id'];
$user_name = $row['username'];
$school = $row['cell_group'];
$avatar = $row['avatar'];
?>
<div class="selectmeWrapper this">
<table class="selectme">
<tr>
<td><span class="selectmeavtspan"><img class="selectmeavatar" src="uploaded/<?php echo $avatar; ?>" /></span></td>
<td><span class="univ"><?php echo $name; ?></span></td>
</tr>
</table>
<span class="uiremovable selected" title="pro/<?php echo $user_name;?>">
<span> <img class="recipavt" src="uploaded/<?php echo $avatar; ?>" /></span>
<span class="selectedName">
<?php echo $name; ?>
<input type="hidden" autocomplete="off"
value="<?php echo $user_name ?>" />
</span>
<i class="fa fa-times"></i>
</span>
</div>
<?php
}
}else{
echo "<p class='noresult'>No Result Found.</p>";
}
}
?>
Table structure for table messages
CREATE TABLE IF NOT EXISTS `messages` (
`user_one` int(11) NOT NULL,
`user_two` int(11) NOT NULL,
`hash` int(11) DEFAULT NULL,
`id` int(11) NOT NULL AUTO_INCREMENT,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=54 ;
and Table structure for table users
CREATE TABLE IF NOT EXISTS `users` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`username` varchar(64) DEFAULT NULL,
`FirstName` varchar(32) DEFAULT NULL,
`LastName` varchar(32) DEFAULT NULL,
`Email` varchar(64) DEFAULT NULL,
`Password` varchar(32) DEFAULT NULL,
`Month` varchar(6) DEFAULT NULL,
`Day` varchar(6) DEFAULT NULL,
`Year` varchar(11) DEFAULT NULL,
`Gender` varchar(6) DEFAULT NULL,
`cell_group` varchar(100) DEFAULT NULL,
`active` varchar(11) DEFAULT NULL,
`avatar` text,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=21 ;
You could use a not in clause
$sql = "
SELECT users.id, users.username,users.FirstName ,
users.LastName , users.avatar ,
users.cell_group
FROM users
WHERE users.id not in (select distinct user_two from " . $message_group_tatable . " )
AND users.username
LIKE concat('%', ". $recipname .", '%')
LIMIT 6
";

select from 2 table and make ordering them

first, sorry for my English ...
what i want is to select from two SQL tables and then make them in a specific order , like in forums ...
i have two table, topic and users, i want to select from both of them a putt author info next to his topic
here is the SQL of Topic and users
CREATE TABLE IF NOT EXISTS `topics` (
`id` int(11) NOT NULL,
`id2` int(11) NOT NULL,
`title` varchar(256) NOT NULL,
`message` longtext NOT NULL,
`author_id` int(11) NOT NULL,
`timestamp` int(11) NOT NULL
) ENGINE=MyISAM DEFAULT CHARSET=utf8;
CREATE TABLE IF NOT EXISTS `users` (
`id` bigint(20) NOT NULL,
`username` varchar(255) NOT NULL,
`password` varchar(255) NOT NULL,
`email` varchar(255) NOT NULL,
`avatar` varchar(255) NOT NULL
) ENGINE=MyISAM DEFAULT CHARSET=utf8;
and the php code might look like this
<?php
$sql = mysql_query(' MySQL query ... ');
while($row = mysql_fetch_array($sql)) {
echo '<p>'.$row['username']'<br>';
echo $row['message'].'<br></p>';
}
?>
is there any way to do it ??
As I understood, what you are looking for is the correct SQL statement to execute. The following simple solution will.
<?php
$sql = mysql_query('SELECT users.username, topics.message FROM `users` INNER JOIN topics ON topics.author_id = users.id');
while($row = mysql_fetch_array($sql)) {
echo '<p>'.$row['username']'<br>';
echo $row['message'].'<br></p>';
}
?>
SELECT * FROM `users` INNER JOIN topics ON topics.author_id = users.id'

how do i select entity from a different table?

i have a commenting system where i am storing the News ID in the comments table to refer and to fetch the value from the newstable, my two table is like this.
New Table,
CREATE TABLE `news` (
`id` int(20) NOT NULL auto_increment,
`timestamp` int(20) NOT NULL,
`title` varchar(255) NOT NULL,
`content` text NULL,
`pic_title` varchar(255) NOT NULL,
`pic_brief` varchar(255) NOT NULL,
`pic_detail` varchar(255) NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
Comments table
CREATE TABLE `comments` (
`id` int(20) NOT NULL auto_increment,
`timestamp` int(20) NOT NULL,
`title` varchar(255) NOT NULL,
`name` varchar(50) NOT NULL,
`email` varchar(50) NOT NULL,
`phone` int(11) NULL,
`location` varchar(50) NOT NULL,
`comment` text NOT NULL,
`approve` tinyint(1) NOT NULL,
`news_id` int(20) NOT NULL,
PRIMARY KEY(`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
in the news_id in the comments table i am storing the id of the news, i want to make the select query from the comments table and it should select the news.title from news referring the news_id in the comments table,
i did something like this.
$query = "SELECT comments.id,
comments.timestamp,
comments.name,
comments.email,
comments.phone,
comments.location,
comments.comment,
news.title FROM
comments, news ORDER BY id DESC LIMIT $from, " . COMM_POST_NUMBER;
how do i make it to fetch only the title from news.title referring the ID from news_id in the comments table?
You need to join both tables:
$query = "SELECT comments.id,
comments.timestamp,
comments.name,
comments.email,
comments.phone,
comments.location,
comments.comment,
news.title
FROM comments INNER JOIN news ON comments.news_id = news.id
ORDER BY id DESC LIMIT $from, " . COMM_POST_NUMBER;
Another notation is:
FROM comments, news WHERE comments.news_id = news.id
P.S. be sure to sanitize your input, don't rely on $from to be an integer, force it to be an integer:
$from = intval($from);
$query = 'SELECT comments.*, news.title
FROM comments
JOIN LEFT news
ON news.id = comments.news_id
ORDER BY id DESC
LIMIT ' . (int) $from . ', ' . COMM_POST_NUMBER;
You need a where clause before the ORDER BY:
... FROM comments, news WHERE comments.news_id = news.id ORDER BY ...
using JOIN
SELECT comments.id,
comments.timestamp,
comments.name,
comments.email,
comments.phone,
comments.location,
comments.comment,
news.title
FROM
comments
join news on news.id=comments.news_id
ORDER BY id DESC
LIMIT .................

Categories