new badge on category list php - php

i am having category sidebar below code
Working Code:
//Showing categories function
function getCats(){
global $db;
$q_cats = "select * from cats ORDER BY cat_name ASC";
$run_cats = mysqli_query($db, $q_cats);
while($row_cat = mysqli_fetch_array($run_cats)){
$cat_id = $row_cat['cat_id'];
$cat_name = $row_cat['cat_name'];
$q_count = "select * from messages where cat_id='$cat_id'";
$run_count = mysqli_query($db, $q_count);
$cat_sms_count = mysqli_num_rows($run_count);
if($cat_sms_count < 1){
$cat_sms_count = 0;
}
echo "<a href='category.php?category=$cat_id' class='list-group-item'>$cat_name<span class='badge'>$cat_sms_count</span></a>";
}//while row END here
$q_tmsgs = "select * from messages";
$run_tcount = mysqli_query($db, $q_tmsgs);
$tsms_count = mysqli_num_rows($run_tcount);
echo "<a href='allindb.php' class='list-group-item t-list'>Total Messages in DB<span class='badge'>$tsms_count</span></a>";
}//Function getCats END here
this working fine but what i want, i want to add a new badge image next to the category name. i tried a lot but failed to do, what i think is the most relevant code.
Please check this code:
//Showing categories function
function getCats(){
global $db;
$q_cats = "select * from cats ORDER BY cat_name ASC";
$run_cats = mysqli_query($db, $q_cats);
while($row_cat = mysqli_fetch_array($run_cats)){
$cat_id = $row_cat['cat_id'];
$cat_name = $row_cat['cat_name'];
$q_count = "select * from messages where cat_id='$cat_id'";
$run_count = mysqli_query($db, $q_count);
$cat_sms_count = mysqli_num_rows($run_count);
//problem area----------------------------------
$q_new = "select * from messages where cat_id='$cat_id' ORDER BY date DESC LIMIT 20";
$run_new = mysqli_query($db, $q_new);
while($new = mysqli_num_rows($run_new)){
$newbadge = $new['cat_id'];
}
if($cat_id==$newbadge){
$newbadge1 = "<img src='images/mynew.gif'>";
}
//--------------------------------------------
if($cat_sms_count < 1){
$cat_sms_count = 0;
}
echo "<a href='category.php?category=$cat_id' class='list-group-item'>$cat_name $newbadge1<span class='badge'>$cat_sms_count</span></a>";
}//while row END here
$q_tmsgs = "select * from messages";
$run_tcount = mysqli_query($db, $q_tmsgs);
$tsms_count = mysqli_num_rows($run_tcount);
echo "<a href='allindb.php' class='list-group-item t-list'>Total Messages in DB<span class='badge'>$tsms_count</span></a>";
}//Function getCats END here

If i understand you correctly you want to show "new badge" on those topics that doesnt have any messages in them. if so you got $q_count
Just replace the while{} inside with an if{}else{}like so:
if($q_count == 0) {
$newbadge1 = "<img src='images/mynew.gif'>";
} else {
$newbadge1 = '';
}
The problem is that you are doing another query that is returning empty array, and therefore you are getting badges on topics that has got messages. So either remove the while{} and replace with the if-else or you can just do a check like:
if(empty($new)) {
$newbadge1 = "<img src='images/mynew.gif'>";
} else {
$newbadge1 = '';
}

Related

Php code returns empty page. tried all other solutions

I am trying to learn php. I wrote code to insert post to database and get posts to display on the home page. I wrote pagination code as well and tried to run it. but as a result php is returning an empty page with no code and no error.
Tried every thing. Went to through most of the answers here. I still can figure out the error.
<?php
$con = mysqli_connect("localhost","root","password","social") or die ("Connection was not established");
//function for getting topics
function getTopics() {
global $con;
$get_topics = "select * from topics";
$run_topics = mysqli_query($con,$get_topics);
while($row=mysqli_fetch_array($run_topics)) {
$topic_id = $row['topic_id'];
$topic_title = $row['topic_title'];
echo "<option value='$topic_id'>$topic_title</option>";
}
}
//function for insert posts to database
function insertPost() {
if(isset($_POST['sub'])) {
global $con;
$title = $_POST['title'];
$content = $_POST['content'];
$topic = $_POST['topic'];
$user = $_SESSION['user_email'];
$get_user = "SELECT * FROM users WHERE user_email = '$user'";
$run_user = mysqli_query($con,$get_user);
$row=mysqli_fetch_array($run_user);
$user_id = $row['user_id'];
$insert = "INSERT INTO posts (user_id,topic_id,post_title,post_content,post_date) VALUES ('$user_id','$topic','$title','$content',NOW())";
$run = mysqli_query($con,$insert);
if($run) {
echo "<h3>Posted to timeline. Looks great.</h3>";
$update = "Update users set posts='yes' where user_id='$user_id'";
$run_update = mysqli_query($con,$update);
}
}
}
//function to get posts
function get_posts() {
global $con;
$per_page=5;
if (isset($_GET['page'])) {
$page = $_GET['page'];
}
else {
$page=1;
}
$start_from = ($page-1)*$per_page;
$get_posts = "SELECT * FROM posts ORDER by 1 DESC LIMIT $start_from, $per_page";
$run_posts = mysqli_query($con,$get_posts);
while($row_posts=mysqli_fetch_array($run_posts)) {
$post_id = $row_posts['post_id'];
$user_id = $row_posts['user_id'];
$post_title = $row_posts['post_title'];
$content = $row_posts['post_content'];
$post_date = $row_posts['post_date'];
//gettin the user who posted the thread
$user = "SELECT * FROM users WHERE user_id='$user_id' AND posts='yes'";
$run_user = mysqli_query($con,$user);
$row_user = mysqli_fetch_array($run_user);
$user_name = $row_user['user_name'];
$user_image = $row_user['user_image'];
//displaying all at once.
echo "<div id='posts'>
<p><img src='user_images/$user_image' width='50' height='50'</p>
<h3><a href='user_profile.php?luser_id=$user_id'>$user_name</h3>
<h3>$post_title</h3>
<p>$post_date</p>
<a href='single.php?post_id=$post_id' style='float:right'><button>See replies</button></a>
</div>";
}
include("pagination.php");
}
?>
pagination code goes like this.
<?php
$query = "SELECT * FROM posts";
$result = mysqli_query($con,$query);
//count the total records
$total_posts = mysqli_num_rows($result);
//using ceil function to divide the total records per page
$total_pages = ceil($total_posts / $per_page);
//going to first page
echo "
<center>
<div id='pagination'>
<a href='welcome.php?page=1'>First Page</a>
";
for ($i=1; $i=$total_pages; $i++) {
echo "<a href='welcome.php?page=$i'>$i</a>";
}
//going to last page
echo "<a href='welcome.php?page=$total_pages'>Last Page</a></center>";
?>

PHP dynamic previous/next links

I have a table called "product".
I'm displaying all the data from PHP product view page by using the id parameter.
With my code:
if(isset($_GET['id'])) {
$id = $_GET['id'];
}
$query = "SELECT * FROM product WHERE id = $id ";
$select_product = $db->query($query);
while($row = $db->fetch_object($select_product)) {
$status = $row->status;
if($status == 'published') {
$title = $row->title;
echo $title;
}
}
I can pull all the data I need. In this example I can echo the title.
But how do I display a dynamic next page link? That goes same for previous link.
When I try with this code:
$query = "SELECT id FROM product";
$select_ids = $db->query($query);
while($row = $db->fetch_object($select_ids)) {
$ids = $row->id;
echo $ids;
}
I can see all the pages from that table. In my case they are 20,21,22...28
Next, I've tried like this:
$query = "SELECT id from product";
$select_ids = $db->query($query);
if($select_ids->num_rows > 0) {
$next = $id + 1;
echo 'Next';
} else {
}
With this code, my "next" link successfully goes to the next page. But, when it finishes with the result, in this case when I'm on page 28, the next dynamic link goes to empty page (29). Also this is not a good approach, because if some page, let's say 25 is deleted, the next link won't skip that page.
How can I improve that dynamic "next" link?
So first of all, you need two queries one for getting the data to display and another for counting the number of rows, also we'll need some additional variables.
Here comes the code:
$page = 1;
if(isset($_GET['page'])) {
$page = $_GET['page'];
}
$numberOfResultsPerPage = 10;
$offset = $numberOfResultsPerPage * ($page - 1)
$count = $db->query("SELECT COUNT(id) as num FROM product");
while($row = $db->fetch_object($count)) {
$numberOfRows = $row->num;
}
$query = "SELECT id FROM product LIMIT ". $offset.", ".$numberOfResultsPerPage;
$select_ids = $db->query($query);
while($row = $db->fetch_object($select_ids)) {
$ids = $row->id;
echo $ids;
}
if($page > 1) {
echo 'Prev';
}
if($page < ceil($numberOfRows / $numberOfResultsPerPage)) {
echo 'Next';
}
UPDATE:
In case you need to just find the next and previous product of the product this is the solution. It is not good if you'll have lots of products but in case the number of products is under 1000 there should not be any problems:
if(isset($_GET['id'])) {
$id = $_GET['id'];
}
$query = "SELECT id from product";
$select_ids = $db->query($query);
$ids = array();
$i = 0;
while($row = $db->fetch_object($select_ids)) {
$ids[$i] = $row->id;
if($row->id == $id) {
$index = $i;
}
$i++;
}
if(isset($ids[$index-1])) {
echo 'Prev';
}
if(isset($ids[$index+1])) {
echo 'Next';
}

Search results with pagination code won't return results

I'm having a hard time getting this search results with pagination code to work. It does successfully grab the search keyword entered in the html form on another page and brings it into this search.php page. if I echo $search I see the keyword on the page. But I get no results even though I should for the query. Can anyone see what might be going on?
require "PDO_Pagination.php";
if(isset($_REQUEST["search_text"]) && $_REQUEST["search_text"] != "")
{
$search = htmlspecialchars($_REQUEST["search_text"]);
$pagination->param = "&search=$search";
echo $search;
$pagination->rowCount("SELECT * FROM stories WHERE stories.genre = $search");
$pagination->config(3, 5);
$sql = "SELECT * FROM stories WHERE stories.genre = $search ORDER BY SID ASC LIMIT $pagination->start_row, $pagination->max_rows";
$query = $connection->prepare($sql);
$query->execute();
$model = array();
while($rows = $query->fetch())
{
$model[] = $rows;
}
}
else
{
$pagination->rowCount("SELECT * FROM stories");
$pagination->config(3, 5);
$sql = "SELECT * FROM stories ORDER BY SID ASC LIMIT $pagination->start_row, $pagination->max_rows";
$query = $connection->prepare($sql);
$query->execute();
$model = array();
while($rows = $query->fetch())
{
$model[] = $rows;
}
}
$query = "SELECT * FROM stories";
if(isset($_REQUEST["search_text"]) && $_REQUEST["search_text"] != "")
{
$search = htmlspecialchars($_REQUEST["search_text"]);
$pagination->param = "&search=$search";
$query .= " WHERE genre LIKE '%$search%'";
}
// No need for else statement.
$pagination->rowCount($query);
$pagination->config(3, 5);
$query .= " ORDER BY SID ASC LIMIT {$pagination->start_row}, {$pagination->max_rows}";
$stmt = $connection->prepare($query);
$stmt->execute();
$model = $stmt->fetchAll();
var_dump($model);
In your query do:
WHERE stories.genre LIKE '%string%');
instead of:
WHERE stories.genre = 'string');
Because the equals will want to literally equal the field.

Undefined variable, unsure why

<?php
$tid = $_GET['tid'];
$id = $_SESSION['userid'];
$sql1 = "SELECT * FROM topics WHERE id='$tid' LIMIT 1";
$res1 = mysqli_query($connect, $sql1) or die(mysqli_error($connect));
while ($row = mysqli_fetch_array($res1, MYSQLI_ASSOC)) {
$title = $row['topic_title'];
$creator = $row['topic_creator'];
}
$sql = "SELECT * FROM users WHERE id='$creator' LIMIT 1";
$user_query = mysqli_query($connect, $sql) or die(mysqli_error($connect));
while ($row = mysqli_fetch_array($user_query, MYSQLI_ASSOC)) {
$name = $row["first"].$row["last"];
}
echo $name;
?>
I'm a little new to PHP, but I've done things exactly like this, but this time I'm getting an error. Everything here works except for $name. I checked my SQL tables and made sure users exist and that there's first and a last area. I don't see what else could be wrong.
Notice: Undefined variable: name in * on line **
Thank you.
Try this code on for size:
<?php
$tid = $_GET['tid'];
$id = $_SESSION['userid'];
$tid = mysqli_escape_string($connect, $tid);
$sql1 = "SELECT * FROM topics WHERE id='{$tid}' LIMIT 1";
$res1 = mysqli_query($connect, $sql1) or die(mysqli_error($connect));
// Check for rows first.
if($res1 and mysqli_num_rows($res1)){
// Use if as while is pointless on LIMIT 1
if($row = mysqli_fetch_array($res1, MYSQLI_ASSOC)) {
$title = $row['topic_title'];
$creator = $row['topic_creator'];
$creator = mysqli_escape_string($connect, $creator);
$sql = "SELECT * FROM users WHERE id='{$creator}' LIMIT 1";
$user_query = mysqli_query($connect, $sql) or die(mysqli_error($connect));
// Check for rows first.
if($user_query and mysqli_num_rows($user_query)){
// Use if as while is pointless on LIMIT 1
if ($row = mysqli_fetch_array($user_query, MYSQLI_ASSOC)) {
$name = $row["first"].$row["last"]; // NO HIT!
}
echo $name;
}else{
echo 'no rows found (query 2).';
}
}
}else{
echo 'no rows found (query 1).';
}
?>
Variable $name is undefined because the $name = ...; line is not reached. So make sure you $sql query actually returns results. It has to in order to define $name.

function call inside a function in php not working

This code is a function calling a function in php. The function call is never called.
function saveSubject(){
$result = mysql_query("select * from term where description='".$_POST['term']."'");
$row = mysql_fetch_array($result, MYSQL_NUM);
global $term;
$term = $row[0];
$x=1;
while(isset($_POST['subCode'.$x])and isset($_POST['subTitle'.$x]) and isset($_POST['subUnit'.$x])){
$code = $_POST['subCode'.$x];
$title = $_POST['subTitle'.$x];
$unit = $_POST['subUnit'.$x];
$query = "INSERT INTO subject(subcode, description, units, termid)
VALUES('".$code."','".$title."',".$unit.",".$term.")";
$result = mysql_query("SELECT * from subject where subcode='".$code."'");
if(mysql_num_rows($result) > 0){
$message = "Subject Code : ".$code;
prompt($message);
}else{
mysql_query($query);
savePre($code, $x);
}
$x++;
}
}
function savePre($code, $y){
$pre = mysql_query("SELECT subject.subcode from subject left join term
on term.termid=subject.termid
left join curriculum on term.termid = curriculum.curriculumid
where term.courseid =".$_POST['course']);
while($row = mysql_fetch_array($pre, MYSQL_NUM)){
$c = $row[0].$y;
if(isset($_POST[$c])){
$result = mysql_query("Select * from pre_requisite where pre_requisites=".$row[0]."and subject=".$code);
if(mysql_num_rows($result) > 0){
$message = "";
}else{
mysql_query("INSERT into pre_requisites(pre_requisite, subject)
values (".$row[0].", ".$code.")");
}
}
}
}
Calling function savePre() in saveSubjec() but the calling is not working. I cannot find out what is wrong. Please help!
Simple...
You code is
$query = "INSERT INTO subject(subcode, description, units, termid)
VALUES('".$code."','".$title."',".$unit.",".$term.")";
$result = mysql_query("SELECT * from subject where subcode='".$code."'");
if(mysql_num_rows($result) > 0)
{
$message = "Subject Code : ".$code;
prompt($message);
}else{
mysql_query($query);
savePre($code, $x);
}
from above code you can imagine that you are inserting record to database and then selecting that record using subcode match where condition so it will always return 1 as output so your else condition will never get execute.
That's the reason why you are not able to call savePre function.
You want to define savePre() function above the saveSubject() function. Use this.
function savePre($code, $y)
{
$pre = mysql_query("SELECT subject.subcode from subject left join term
on term.termid=subject.termid
left join curriculum on term.termid = curriculum.curriculumid
where term.courseid =".$_POST['course']);
while($row = mysql_fetch_array($pre, MYSQL_NUM))
{
$c = $row[0].$y;
if(isset($_POST[$c]))
{
$result = mysql_query("Select * from pre_requisite where pre_requisites=".$row[0]."and subject=".$code);
if(mysql_num_rows($result) > 0){
$message = "";
}else{
mysql_query("INSERT into pre_requisites(pre_requisite, subject)
values (".$row[0].", ".$code.")");
}
}
}
}
function saveSubject()
{
$result = mysql_query("select * from term where description='".$_POST['term']."'");
$row = mysql_fetch_array($result, MYSQL_NUM);
global $term;
$term = $row[0];
$x=1;
while(isset($_POST['subCode'.$x])and isset($_POST['subTitle'.$x]) and isset($_POST['subUnit'.$x]))
{
$code = $_POST['subCode'.$x];
$title = $_POST['subTitle'.$x];
$unit = $_POST['subUnit'.$x];
$result = mysql_query("SELECT * from subject where subcode='".$code."'");
if(mysql_num_rows($result) > 0){
$message = "Subject Code : ".$code;
prompt($message);
}
else
{
$query = "INSERT INTO subject(subcode, description, units, termid)
VALUES('".$code."','".$title."',".$unit.",".$term.")";
mysql_query($query);
savePre($code, $x);
}
$x++;
}
}

Categories