Create function from a mysql query - php

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);
}

Related

Showing six latest PhpBB posts instead of six copies of latest post

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.)
}

How to limit the amount of search results on each page like Google?

I am trying to limit the amount of search results on each page like Google does. I am also using a SQL database to organize my keywords and everything. Here is my code
<?php
$q = $_GET['q'];
$terms = explode(" ", $q);
//connect
mysql_connect("localhost", "root", "") or die ("Could Not Connect");
mysql_select_db("search") or die ("Could Not Connect To database");
$query = "SELECT * FROM search ";
$i=1;
foreach ($terms as $each){
if ($i == 1) {
$query .= "WHERE ";
$query .= "keywords LIKE '" . mysql_real_escape_string("%" . $each . "%") . "' ";
} else {
$query .= "OR keywords LIKE '" . mysql_real_escape_string("%" . $each . "%") . "' ";
}
$i++;
}
$query = mysql_query($query);
$numrows = mysql_num_rows($query);
if ($numrows > 0)
{
while($row = mysql_fetch_assoc($query))
{
$id = $row['id'];
$title = $row['title'];
$description = $row['description'];
$keywords = $row['keywords'];
$link = $row['link'];
echo "<h3><a href='$link'>$title</a></h3><h4>$link</h4>$description<br /><br />";
}
} else {
echo "<b>No Results Found</b><br><br>Suggestions:<br>
Make sure all words are spelled correctly.<br>
Try different keywords.<br>
Try more general keywords.";
}
//disconnect
mysql_close();
?>
After your foreach ($terms as $each){} you need to add an ORDER BY and LIMIT to the query, like so:
$query .= "ORDER BY keywords LIMIT 0, 10";
That will give you the first 10 results. Alter the LIMIT vars as needed. The first number is the offset (zero based, aka first result is 0, sixth result is 5) and the second number is the number of rows to return.
The ORDER BY helps with consistent results. You don't need it, but sometimes results can be weird.
See this question for more info if you need it.

Diplay items for category PHP and echo categories as link to each view

Hello im learning so im sorry if this is a fool question. (also sorry about my bad english)
Im trying to display the items from a particular category.
In my Database, i have set my categories like this.
And the Products or Items like this,
Im using this code to display tree categories.
function hasChild($parent_id)
{
$sql = "SELECT COUNT(*) as count FROM category WHERE parent_id = '" . $parent_id . "'";
$qry = mysql_query($sql);
$rs = mysql_fetch_array($qry);
return $rs['count'];
}
function CategoryTree($list,$parent,$append)
{
$list = '<li>'.$parent['name'].'</li>';
if (hasChild($parent['id'])) // check if the id has a child
{
$append++;
$list .= "<ul class='child child".$append."'>";
$sql = "SELECT * FROM category WHERE parent_id = '" . $parent['id'] . "'";
$qry = mysql_query($sql);
$child = mysql_fetch_array($qry);
do{
$list .= CategoryTree($list,$child,$append);
}while($child = mysql_fetch_array($qry));
$list .= "</ul>";
}
return $list;
}
function CategoryList()
{
$list = "";
$sql = "SELECT * FROM category WHERE (parent_id = 0 OR parent_id IS NULL)";
$qry = mysql_query($sql);
$parent = mysql_fetch_array($qry);
$mainlist = "<ul class='parent'>";
do{
$mainlist .= CategoryTree($list,$parent,$append = 0);
}while($parent = mysql_fetch_array($qry));
$list .= "</ul>";
return $mainlist;
}
But i cant find a good way to convert the categories in links, so each time a users clic one category i will display the items for that category..
What would be the best for that.
If you can point me in the right direction, some tutorial, or something, would be really , really great.
It sounds like you are looking for some sort of java tree viewer, like this example?
http://dftree.sourceforge.net/dftree/example.html
There are several open source options for this (I have no experience of the one I list above, I just use it as an example). I'm sure I have used a tree viewer in the past that took a list format like you are using - I suggest you have a search around sourceforge.
Your question is not foolish, but is quite long... and many of us are quite lazy :-)
Ok i solve this
This is the code for the page with the menu and categories
<?php
function hasChild($parent_id)
{
$sql = "SELECT COUNT(*) as count FROM category WHERE parent_id = '" . $parent_id . "'";
$qry = mysql_query($sql);
$rs = mysql_fetch_array($qry);
return $rs['count'];
}
function CategoryTree($list,$parent,$append)
{
$productpage = "index.php";
$list = '<li><a href='.$productpage.'?'.'cat='.$parent['id'].'>'.$parent['name'].'</a></li>';
if (hasChild($parent['id'])) // check if the id has a child
{
$append++;
$list .= "<ul class='child child".$append."'>";
$sql = "SELECT * FROM category WHERE parent_id = '" . $parent['id'] . "'";
$qry = mysql_query($sql);
$child = mysql_fetch_array($qry);
do{
$list .= CategoryTree($list,$child,$append);
}while($child = mysql_fetch_array($qry));
$list .= "</ul>";
}
return $list;
}
function CategoryList()
{
$list = "";
$sql = "SELECT * FROM category WHERE (parent_id = 0 OR parent_id IS NULL)";
$qry = mysql_query($sql);
$parent = mysql_fetch_array($qry);
$mainlist = "<ul class='parent'>";
do{
$mainlist .= CategoryTree($list,$parent,$append = 0);
}while($parent = mysql_fetch_array($qry));
$list .= "</ul>";
return $mainlist;
}
?>
And the code for the product page
<?php
$producto = mysql_escape_string($_GET['producto']);
$tablename = "productos";
$res = mysql_query("SELECT * FROM `$tablename` WHERE `id` = '$producto'");
$row = mysql_fetch_assoc($res);
$uid = $row["id"];
$titulo = $row["titulo"];
$descripcion = $row["descripcion"];
$modelo = $row["modelo"];
$img = $row["img"];
// echo the output to browser or compound an output variables here
echo "ID = $uid
<br />Titulo = $titulo
<br>Descripcion = $descripcion
<br>Modelo = $modelo
<br>Imagen = <img src=\"../admin/$img\" width=\"40px\" height=\"40px\" >
<hr />";
?>

PHP/MySQL Multi table selections

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);

How can I make this simple block shorter and better?

I'm using the following not well thought code block to retrieve categories and it's topics.
$query1 = "SELECT * from categories";
$result = mysql_query($query1);
while ($out = mysql_fetch_assoc($result)){
//category
print '<h2>' . $out['name'] . '</h2>';
$query2 = "SELECT * from topics where fkid = $out[id]";
$result2 = mysql_query($query2);
while($top = mysql_fetch_assoc($result2)){
//topic
print $top['name'] . '<br>';
}
}
The above does the trick. I know this is not the most practical and this being the reason I ask the group.
How can I better this so it's more practical and simple?
A classical case for a JOIN:
SELECT * FROM categories JOIN topics ON categories.id = topic.fkid ORDER BY categories.name;
Then to print, we only print the header if it has changed (thanks, Rajasur!):
$catname = "";
while ($out = mysql_fetch_assoc($result))
{
if ($out["name"] != $catname) // maybe need strcmp here
{
$catname = $out["name"];
print($catname)
}
/* print the rest */
}
Just use a single query that joins the two tables.
$query = "SELECT categories.name AS category_name, topics.name AS topic_name
FROM categories JOIN topics ON categories.id = topics.fkid
ORDER BY categories.name ASC, topics.name ASC";
$resultSet = mysql_query($query);
$currentCategory = "";
while ($cRecord = mysql_fetch_assoc($resultSet)) {
if ($currentCategory != $cRecord['category_name']) {
$currentCategory = $cRecord['category_name'];
echo "<h2>" . $currentCategory . "</h2>";
}
echo $cRecord['topic_name'] . "<br/>";
}
mysql_close($resultSet);

Categories