Trying to display six of the latest posts from my PhpBB installation. I'm happy with how it's all working, however it's showing six copies of the same (most recent) post, and not size unique latest posts.
Just to confirm, I have seven total posts on the forums.
<?php
$con = mysqli_connect("localhost", "dbuser", "dbpass", "dbname");
$users = mysqli_query($con, "SELECT * FROM phpbb_user_group WHERE group_id='8'");
while($row = mysqli_fetch_array($users)) {
$developers[] = $row["user_id"];
}
$post = mysqli_query($con, "SELECT * FROM phpbb_posts");
while($row = mysqli_fetch_array($post)) {
$topic_id = $row["topic_id"];
$forum_id = $row["forum_id"];
$post_id = $row["post_id"];
$post_text = $row["post_text"];
$post_time = $row["post_time"];
}
$username = mysqli_query($con, "SELECT * FROM phpbb_users WHERE user_id='2'");
while($row = mysqli_fetch_array($username)) {
$postauthor = $row["username"];
if (strlen($post_text) > 10)
$post_text = wordwrap($post_text, 120);
$post_text = explode("\n", $post_text);
$post_text = $post_text[0] . '...';
$result = mysqli_query($con, "SELECT * FROM phpbb_posts WHERE poster_id='2' LIMIT 6");
while($row = mysqli_fetch_array($result)) {
$content = '<div onclick="location.href=\'http://test.mythros.net/forum/viewtopic.php?f=' . $forum_id . '&p=' . $topic_id . '#p' . $post_id . '\';" class="forum-latest-box">';
$content .= '<div class="forum-latest-userbar">';
$content .= '<div class="forum-latest-avatar">';
$content .= '<img src="https://minotar.net/helm/' . $postauthor . '/40.png">';
$content .= '</div>';
$content .= '<h1>' . $postauthor . '</h1>';
$content .= '</div>';
$content .= '<div class="forum-latest-content">';
$content .= '<div class="forum-latest-text">';
$content .= '"' . $post_text . '"';
$content .= '</div>';
$content .= '<div class="forum-latest-meta">';
$content .= gmdate("F j, Y, g:i a", $post_time);
$content .= '</div>';
$content .= '</div>';
$content .= '</div>';
echo $content;
}
?>
You can solve this problem by using a single loop and getting your post data and user information at the same time using combined query to the phpbb_posts table and phpbb_users table:
## Line break added to the query for legibility
$result = mysqli_query($con,
"SELECT
p.post_id AS post_id,
p.topic_id AS topic_id,
p.forum_id AS forum_id,
p.post_time AS post_time,
p.post_subject AS subject,
p.post_text AS post_text
IFNULL(m.username, 'Guest') AS username,
FROM phpbb_posts AS p
LEFT JOIN phpbb_users AS m ON (m.user_id = p.poster_id)
ORDER BY phpbb_posts.post_time DESC LIMIT 6");
while($row = mysqli_fetch_array($result)) {
# $row now contains the post information and the user info, so you can grab all your data,
# process the post text, and print it out at the same time.
$post_text = $row["post_text"];
# do your text transformation
if (strlen($post_text) > 10)
... (etc.)
# now set up your content
$content = '<div onclick="location.href=\'http://test.mythros.net/forum/viewtopic.php?f=' . $row["forum_id"] .'&p=' . $row["topic_id"] . '#p' . $row["post_id"] . '\';" class="forum-latest-box">';
... (etc.)
}
Related
I have a specific query which is reading the 5 latest articles out of my database for category (mysql column) "sport"
I would like to run mulitiple queries, one for sport, one for cars, one for books, etc. Instead of rewriting the full query multiple times and replace the category sport by cars/books etc I would like to know if it possible to rebuild it to a function in which I input the category (like sports in line 2) and it outputs a string $sports (like in line 10/11) with all retrieves from the database as defined in the query.
// Build feed source for the latest News of Sport
$sqlCommand = "SELECT * FROM feeds where category like 'Sport' ORDER BY id DESC LIMIT 5";
$query = mysqli_query($myConnection, $sqlCommand) or die (mysqli_error());
$sport = '';
while ($row = mysqli_fetch_array($query)) {
$fid1 = $row["id"];
$title1 = $row["title"];
$description1 = $row["description"];
$sport .= '<h2><b>' . $title1 . '</b></h2>';
$sport .= '' . $description1 . '<br/>';
}
mysqli_free_result($query);
This is how I finally resolved it:
function nieuws ($category,$color) {
global $myConnection;
$sqlCommand = "SELECT * FROM feeds where category like '$category' ORDER BY id DESC LIMIT 1";
$query = mysqli_query($myConnection, $sqlCommand) or die (mysqli_error());
$output = '';
$output = "<div class=headlines style=background:$color><a class=newslink href='$category'>$category</a></div>";
while ($row = mysqli_fetch_array($query)) {
$fid1 = $row["id"];
$title1 = $row["title"];
$titleseo1 = seofy($title1);
$description1 = $row["description"];
$photo1 = $row["photo"];
if ('' == $photo1) {$photo1='images/pic1.jpg';};
$output .= "<div class=news2 style=background:#F0F8FF><img src='$photo1' alt='photo' style='width:200px;height:150px;object-fit:cover;border:0;margin:0px 5px 0px 0px;float:left'>"; //object-fit: cover zorgt dat het origineel het plaatje vult zonder distortion, is in principe cropping
$output .= '<b>' . $title1 . '</b></br>';
$output .= '' . $description1 . '<br/>';
$output .= "</div>";
}
mysqli_free_result($query);
}
As the data has grown the need for pagination is of great importance. Everything works fine. I have a limit in my SELECT statement and count the rows. The goal is to have pagination at the bottom of the page with the limit of 10. The page contains the latest rows in the database. Do i need to have
<?php
$servername = "localhost";
$username = "";
$password = "";
$dbname = "";
$conn = new mysqli($servername, $username, $password, $dbname);
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$nr = 0;
$count = mysql_query("SELECT count(*) AS TOTAL FROM quotes");
$row = mysql_fetch_array($sum);
$sql = "SELECT * FROM quotes ORDER BY date DESC limit 10";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
$output = "";
while($row = $result->fetch_assoc() ) {
$topic = trim($row["topic"]);
$quote = trim($row["quote"]);
$author = trim($row["author"]);
$id = trim($row["id"]);
$output .= injectNColumnWrapper(3, $nr, "container row", $nr);
$output .="<div class='col s12 m6 l4 z-depth-1'>";
$output .="<div class='card-panel grey darken-4 white-text center'>";
$output .=" <h5>Citat: {$id}</h5>";
$output .="</div>";
$output .="<pre class='flow-text black-text' wrap='soft'>";
$output .="<p class='flow-text-p citat'>"{$quote}"</p>";
$output .="<p style='font-weight:bold; class='flow-text-p author'>{$author}</p>";
$output .="<p class='flow-text-p topic'>{$topic}</p>";
$output .="</pre>";
$output .="<div class='content_wrapper'>";
$output .="<h4></h4>";
$output .="<div class='voting_wrapper' id='vote-{$id}'>";
$output .="<div class='voting_btn'>";
$output .="<div class='up_button'> </div>";
$output .="<span class='up_votes'>0</span>";
$output .="</div>";
$output .="<div class='voting_btn'>";
$output .="<div class='down_button'> </div>";
$output .="<span class='down_votes'>0</span>";
$output .="</div>";
$output .="<br>";
$output .="</div>";
$output .="</div>";
$output .="</div>";
$nr++;
}
$output .= "</div>";
echo $output;
}else {
echo "0 results";
}
$conn->close();
function injectNColumnWrapper($cols_per_row, $closePoint, $cssClass="container row", $nthElem=""){
$blockDisplay = "";
if( ($closePoint == 0) ){
$blockDisplay = "<div class='" . $cssClass . " container_nr_" . $nthElem . "'>" . PHP_EOL;
}else if( ($closePoint % $cols_per_row) == 0 && ($closePoint != 0) ){
$blockDisplay = "</div><div class='" . $cssClass . " container_nr_" . $nthElem . "'>" . PHP_EOL;
}
return $blockDisplay;
}
?>
$limit = 10;
$start = $nr * $limit
$sql = "SELECT * FROM quotes ORDER BY date DESC limit $start $limit";
Where $nr is number of current page -1, so if you have page 1, it should be 0, if 2 then 1, etc.
To get number of pages, you ned to take all your results count and make division by limit so for example 100/10 = 10 pages. Simple for loop should render pages.
Use offset in your query.
You may display a set of links in your pagination, then catch the param from the URL and finally construct the query with the proper offset.
Pagination links:
// Note: $row['TOTAL'] comes from your counting sql (count(*))
for ($i = 0; $i< $row['TOTAL']; $i++) {
echo " <a href='?p=$i'>$i</a> |";
}
Get the requested page in your URL:
$requestedPage = !empty($_GET['p']) ? intval($_GET['p']) : 0;
Construct the query:
$pagination = 10 * $requestedPage;
$sql = "SELECT * FROM quotes ORDER BY date DESC limit 10 OFFSET $pagination";
You should give start and length (offset) values to limit data in MySQL for pagination. EG :
SELECT * FROM table_name WHERE your_condition LIMIT 0,9 - to fetch first 10 records
SELECT * FROM table_name WHERE your_condition LIMIT 10,19 - to fetch second set of 10 records
Refer for example. And it is a duplicate question
I have an issue with the loading of this website - http://decoded.ro/l2tales. The problem is caused by these 2 PHP scripts:
<?php
mysql_connect('example.com','XXXXXXX', 'XXXXXXXX') or die(mysql_error());
mysql_select_db('dbname');
$query = mysql_query("SELECT * FROM `smf_topics` WHERE `id_board` = '2' ORDER BY `id_topic` DESC LIMIT 5");
//echo '<span style="color: white;">DARK' . $query . '</span>';
while($row = mysql_fetch_assoc($query))
{
$id_topic = $row['id_topic'];
$query2 = mysql_query("SELECT * FROM `smf_messages` WHERE `id_topic` = $id_topic");
$row2 = mysql_fetch_assoc($query2);
echo '<div class="page-title">';
echo '<h1>' . htmlspecialchars_decode(substr($row2['subject'], 0 ,200)) . '</h1>';
echo '<p style="color: #eed883;">';
echo 'Author: ' . $row2['poster_name'];
echo '</p>';
echo '<p>';
echo $row2['body'];
echo '</p>';
echo '</div>';
}
?>
<?php
mysql_connect('example.com','XXXXXXX', 'XXXXXXXX') or die(mysql_error());
mysql_select_db('dbname');
$query = mysql_query("SELECT * FROM `smf_topics` WHERE `id_board` = '4' ORDER BY `id_topic` DESC LIMIT 5");
//echo '<span style="color: white;">DARK' . $query . '</span>';
while($row = mysql_fetch_assoc($query))
{
$id_topic = $row['id_topic'];
$query2 = mysql_query("SELECT * FROM `smf_messages` WHERE `id_topic` = $id_topic");
$row2 = mysql_fetch_assoc($query2);
$count = strlen($row2['subject']);
if($count > '59')
$dots = '...';
else
$dots = '';
echo '<li>';
echo '<a href="http://forum.l2tales.com//index.php?topic=' . $row['id_topic'] . '/" title="' . htmlspecialchars_decode(substr($row2['subject'], 0 ,75)) . '" target="_blank">';
echo '<span>' . htmlspecialchars_decode(substr($row2['subject'], 0 ,59)) . $dots . '</span>';
echo '<p>';
echo 'Author: ' . $row2['poster_name'];
echo '</p>';
echo '</a>';
echo '</li>';
}
?>
These PHP scrips are fetching from a SMF database on hosted on server B (will explain later) latest 5 topics.
So i have 2 servers. On server A (which is decoded.ro/l2tales) it works fine, is loading is almost instant for me. On server B, where the forum is hosted, the website loads in years.
Here you can see a adress for the website hosted on server B - http://l2tales.com/dark (At first you will see a blank page but the website is still loading, just wait until it loads completly).
Why on the same server with the forum is so slow but on a different server is instant?
Thanks
I'm trying to select multiple rows from one table, depending on the ID given from another table.
I've got it half working with the code below, however it echo's out each blog multiple times depending on how many different tags are assigned to it, how would I go about so it displays multiple tag's on one copy of the blog post?
$sqlCommand = "SELECT blogid, blogtitle, content, blogtime, category, blogseourl, author FROM blog ORDER BY blogtime DESC";
$query = mysqli_query($myConnection, $sqlCommand) or die (mysqli_error());
$blogDisplay = '';
while ($row = mysqli_fetch_array($query)) {
$blogid = $row["blogid"];
$blogtitle = $row["blogtitle"];
$content = $row["content"];
$blogtime = $row["blogtime"];
$category = $row["category"];
$blogseourl = $row["blogseourl"];
$author = $row["author"];
$contentshort = substr($content, 0, 250);
$sqlCommand2 = "SELECT tag FROM blogtags WHERE blogid='$blogid'";
$query2 = mysqli_query($myConnection, $sqlCommand2) or die (mysqli_error());
while ($row = mysqli_fetch_array($query2)) {
$tag = $row['tag'];
$blogDisplay .= '<h1> ' . $blogtitle . ' </h1> ' . $contentshort . '... Read More...<br /><br /> ' . $author . ' posted on ' . $blogtime . ' | Category: ' . $category . ' | Tags: ' . $tag . ' | ';
}
}
mysqli_free_result($query);
So everything is working correctly apart from it echoing multiple $blogDisplay's for each tag.
Anyone got any ideas?
You have to divide the blogDisplay into two sections, and list the tabs in between.
Or you have to buffer up the taglist and insert it as a parameter into $blogDisplay
The first one is easiest:
$sqlCommand = "SELECT blogid, blogtitle, content, blogtime, category, blogseourl, author FROM blog ORDER BY blogtime DESC";
$query = mysqli_query($myConnection, $sqlCommand) or die (mysqli_error());
$blogDisplay = '';
while ($row = mysqli_fetch_array($query)) {
$blogid = $row["blogid"];
$blogtitle = $row["blogtitle"];
$content = $row["content"];
$blogtime = $row["blogtime"];
$category = $row["category"];
$blogseourl = $row["blogseourl"];
$author = $row["author"];
$contentshort = substr($content, 0, 250);
$sqlCommand2 = "SELECT tag FROM blogtags WHERE blogid='$blogid'";
$query2 = mysqli_query($myConnection, $sqlCommand2) or die (mysqli_error());
/*first part, all the html before the taglist */
$blogDisplay .= '<h1> ' . $blogtitle . ' </h1> ' . $contentshort . '... Read More...<br /><br /> ' . $author . ' posted on ' . $blogtime . ' | Category: ' . $category . ' | Tags: ';
while ($row = mysqli_fetch_array($query2)) {
$tag = $row['tag'];
/**add the taglist*/
$blogDisplay .= $tag.' ';
}
/**last part, all the html after the taglist*/
$blogDisplay .= ' | ';
}
mysqli_free_result($query);
I have been working on a social network, i have a fanpages table that a user can create a profile for their favorite band or celebrity and another table called friends where they can subscribe to the fanpages. i then want the requests to appear in notifications for the fanpage admin to except.
after the first sql query it returns fanpages with multiple values but if i echo the next $sql query it shows that its only selecting one result to query instead of all of them.
so basically i need to query fanpages table for all fanpages created_by the user logged on ($log_username), then i need to take those fanpages and query the friends table to find out if anyone has requested to subscribe to the users fan pages??
thanks for your help Michael
<?php
$fanpage_requests = '';
$fansql = "SELECT created_by, fanpage_name FROM `fanpages` WHERE created_by = '$log_username' ";
$fanquery = mysqli_query($db_conx, $fansql);
$fannumrows = mysqli_num_rows($fanquery);
if($fannumrows < 1){
$fanpage_requests = 'No friend requests';
} else {
while($row = mysqli_fetch_array($fanquery, MYSQLI_ASSOC)) {
$fanpage_name = $row["fanpage_name"];
$created_by = $row["created_by"];
$fansubSql = "SELECT * FROM friends WHERE user2='$fanpage_name' AND accepted='0' ORDER BY datemade ASC";
$fansubQuery = mysqli_query($db_conx, $fansubSql);
$fansubNumrows = mysqli_num_rows($fansubQuery);
//print_r ($fansubNumrows);
if($fansubNumrows < 1){
$fanpage_requests = "blah blah";
}
print_r ($fansubNumrows);
while ($fansubRow = mysqli_fetch_array($fansubQuery, MYSQLI_ASSOC)) {
$fansubreqID = $fansubRow["id"];
$fansubuser1 = $fansubRow["user1"];
$fansubdatemade = $fansubRow["datemade"];
$fansubdatemade = strftime("%B %d", strtotime($fansubdatemade));
$fansubthumbquery = mysqli_query($db_conx, "SELECT avatar FROM users WHERE username='$fansubuser1' LIMIT 1");
$fansubthumbrow = mysqli_fetch_row($fansubthumbquery);
$fansubuser1avatar = $fansubthumbrow[0];
$fansubuser1pic = '<img src="user/'.$fansubuser1.'/'.$fansubuser1avatar.'" alt="'.$fansubuser1.'" class="user_pic">';
if($fansubuser1avatar == NULL){
$fansubuser1pic = '<img src="images/avatardefault.jpg" alt="'.$fansubuser1.'" class="user_pic">';
}
$fanpage_requests .= '<div id="friendreq_'.$fansubreqID.'" class="friendrequests">';
$fanpage_requests .= ''.$fansubuser1pic.'';
$fanpage_requests .= '<div class="user_info" id="user_info_'.$fansubreqID.'">'.$fansubdatemade.' '.$fansubuser1.' requests friendship<br /><br />';
$fanpage_requests .= '<button onclick="fanReqHandler(\'accept\',\''.$fansubreqID.'\',\''.$fansubuser1.'\',\'user_info_'.$fansubreqID.'\')">accept</button> or ';
$fanpage_requests .= '<button onclick="fanReqHandler(\'reject\',\''.$fansubreqID.'\',\''.$fansubuser1.'\',\'user_info_'.$fansubreqID.'\')">reject</button>';
$fanpage_requests .= '</div>';
$fanpage_requests .= '</div>';
}
}
}
?>
print_r output is now 001110 and i get blah blah
Ok, so having established that you need to close your loop later, the reason it does not work correctly is because now you are using the same variables in the different loops, so values are being overwritten (e.g. $query).
You need to differentiate your loops clearly, in terms of all variables that need to be different:
<?php
$friend_requests = '';
$sql = "SELECT created_by, fanpage_name FROM `fanpages` WHERE created_by = '$log_username' ";
$query = mysqli_query($db_conx, $sql);
$numrows = mysqli_num_rows($query);
if($numrows < 1){
$friend_requests = 'No friend requests';
} else {
while($row = mysqli_fetch_array($query, MYSQLI_ASSOC)) {
$fanpage_name = $row["fanpage_name"];
$created_by = $row["created_by"];
$friendsSql = "SELECT * FROM friends WHERE user2='$fanpage_name' AND accepted='0' ORDER BY datemade ASC";
$friendsQuery = mysqli_query($db_conx, $friendsSql);
$friendsNumrows = mysqli_num_rows($friendsQuery);
$fanpage_requests = "$friendsSql";
if($friendsNumrows < 1){
$fanpage_requests = "$fanpage_name"; **//this shows that only 1 query is being queried in this second sql statement**
}
while ($friendsRow = mysqli_fetch_array($friendsQuery, MYSQLI_ASSOC)) {
$reqID = $friendsRow["id"];
$user1 = $friendsRow["user1"];
$datemade = $friendsRow["datemade"];
$datemade = strftime("%B %d", strtotime($datemade));
$thumbquery = mysqli_query($db_conx, "SELECT avatar FROM users WHERE username='$user1' LIMIT 1");
$thumbrow = mysqli_fetch_row($thumbquery);
$user1avatar = $thumbrow[0];
$user1pic = '<img src="user/'.$user1.'/'.$user1avatar.'" alt="'.$user1.'" class="user_pic">';
if($user1avatar == NULL){
$user1pic = '<img src="images/avatardefault.jpg" alt="'.$user1.'" class="user_pic">';
}
$fanpage_requests .= '<div id="friendreq_'.$reqID.'" class="friendrequests">';
$fanpage_requests .= ''.$user1pic.'';
$fanpage_requests .= '<div class="user_info" id="user_info_'.$reqID.'">'.$datemade.' '.$user1.' requests friendship<br /><br />';
$fanpage_requests .= '<button onclick="fanReqHandler(\'accept\',\''.$reqID.'\',\''.$user1.'\',\'user_info_'.$reqID.'\')">accept</button> or ';
$fanpage_requests .= '<button onclick="fanReqHandler(\'reject\',\''.$reqID.'\',\''.$user1.'\',\'user_info_'.$reqID.'\')">reject</button>';
$fanpage_requests .= '</div>';
$fanpage_requests .= '</div>';
}
}
}
?>