Making query show latest updated - php

So I have a script that displays all the topics posted with the information about the topic, I was wondering if anybody could help me make it so whenever somebody comments on it or if the post is edited that it will bump it to the first line echod of the query?
function getReplies($id){
$q = #mysql_query("SELECT reply_content, reply_date, reply_by FROM replies WHERE reply_id='$id'");
if(!$q){
echo 'Error: '.mysql_error();
}
$res = mysql_fetch_array($q);
$q2 = #mysql_query("SELECT `topic_subject` FROM `topics` WHERE `topic_id`='$id'");
if(!$q2){
echo 'Error: '.mysql_error();
}
$res2 = mysql_fetch_array($q2);
if($_SESSION['id'] == $res['reply_by']){
echo '<div class="panel panel-default">
<div class="panel-heading"><b>'.$res2['topic_subject'].'</b></div>
<div class="panel-body">
'.nl2br($res['reply_content']).'
</div>
<div class="panel-footer">
Posted By <strong>'.getOwner($res['reply_by']).'</stong>
on <strong>'.$res['reply_date'].'</strong><br />
Edit | Delete
</div>
</div>
</div>';
} else {
echo'<div class="panel panel-default">
<div class="panel-heading"><b>'.$res2['topic_subject'].'</b></div>
<div class="panel-body">
'.nl2br($res['reply_content']).'
</div>
<div class="panel-footer">
Posted By <strong>'.getOwner($res['reply_by']).'</stong>
on <strong>'.$res['reply_date'].'</strong><br />
</div>
</div>
</div>';
}
}
Comments:
Posts:
Topics:

Try to change your first query and grant it an ORDER BY, perhaps?
$q = "SELECT reply_content, reply_date, reply_by
FROM replies
WHERE reply_id='$id'
ORDER BY reply_date DESC";
It would seem to me also, that you are using two queries, where you only really need to be using one.
UPDATE: Optimized code, try not to repeat yourself, and join queries
function getReplies($id) {
$query = "SELECT replies.reply_content,
replies.reply_date,
replies.reply_by
topics.topic_subject
FROM replies,
topics
WHERE replies.reply_id = topics.topic_id
AND replies.reply_id = '$id' " . //<== PS: You should sanitize this $id parameter
" ORDER BY replies.reply_date DESC";
// You can replace the replies.reply_date column by whatever you end up with for sorting
// Important note - Look into mysqli, mysql is deprecated and too old to be used these days.
$q = #mysql_query($query);
if(!$q) {
echo 'Error: '.mysql_error();
}
$res = mysql_fetch_array($q);
$output = '
<div class="panel panel-default">
<div class="panel-heading"><b>'.$res['topic_subject'].'</b></div>
<div class="panel-body">
'.nl2br($res['reply_content']).'
</div>
<div class="panel-footer">
Posted By <strong>'.getOwner($res['reply_by']).'</stong>
on <strong>'.$res['reply_date'].'</strong><br />';
if($_SESSION['id'] == $res['reply_by'])
$output .= 'Edit | Delete';
$output .= '
</div>
</div>
</div>';
echo $output;
}

Related

How to dislpay all animals that are status = 1 in PHP

I'm making an adoption website for a project.
I'm trying to display all animals whose status = 1 but the animals whose status = 0 keeps appearing in the category.
Is something wrong with my code? suggestions and corrections are welcome.
Thank you!
function.php
function get_animals($cat_id='', $animal_id='')
{
global $con;
$query = "SELECT * FROM animals WHERE status= 1";
if($cat_id!='')
{
$query = "SELECT * FROM animals WHERE category_name='$cat_id'";
}
if ($animal_id!='')
{
$query = "SELECT * FROM animals WHERE id=$animal_id";
}
return $result = mysqli_query($con,$query);
}
This is my animals.php file
<?php
$cat_id = '';
if(isset($_GET['id']))
{
$cat_id = mysqli_real_escape_string($con,$_GET['id']);
}
$particular_animal = get_animals($cat_id);
?>
<!-- End Navigation -->
<!-- Product Grid -->
<div class="container mt-5 ">
<div class="row">
<?php
if(mysqli_num_rows($particular_animal))
{
while($row = mysqli_fetch_assoc($particular_animal))
{
?>
<div class="col-md-4 product-grid">
<div class="row">
<div class="image border border-info bg-light">
<a href="animal_details.php? a_id=<?php echo $row ['id'] ?>">
<img src="admin/image/<?php echo $row['img']?>" class="w-100" alt="">
</a>
<h4 class="text-center mt-2 text-info font-weight-bold"><?php echo $row ['name'] ?></h4>
<p class="text-center mt-2"><?php echo $row ['gender'] ?></p>
</div>
</div>
</div>
<?php
}
}
else
{
echo "record not here";
}
?>
</div>
</div>
You're overwriting your $query (the one with the status) when $cat_id or $animal_id is set. Instead, add to the WHERE clause of your first query:
$query = "SELECT * FROM animals WHERE status= 1";
if($cat_id != '') {
$query .= " AND category_name='$cat_id'";
}
if ($animal_id != '') {
$query .= " AND id=$animal_id";
}
If your function gets a category id or an animal id, then your query is overriden and your status criteria is lost. This is a 1-command solution:
function get_animals($cat_id='', $animal_id='')
{
return mysqli_query($con,"SELECT * FROM animals WHERE status= 1" .
($cat_id ? " AND category_name = {$cat_id} " : "").
($animal_id ? " AND animal_id = {$animal_id} " : ""));
}

PHP function not showing data from dropdown menu

Currently creating 2 dropdown menus, one for category and one for subcategory. My current function shows all data on the page only for subcategories but not for categories. Why is this happening?
Current Functionality: User selects a category, page refreshes and is blank. Once user selects SUBcategory it shows all products in that subcategory.
Desired Functionality: User selects a category, page refreshes and shows all products in that category. Once user selects subcategory it shows all products in that subcategory.
function populate_search_catsub()
{
global $link;
$subcatt = "";
$query = 'SELECT * FROM item';
$result = mysqli_query($link, $query);
$catt = $_GET['catt'];
if (isset($_GET['subcatt'])) {
$subcatt=$_GET['subcatt'];
}
$nbprod = mysqli_query($link, "SELECT * FROM `item` WHERE cat='$catt' AND field='$subcatt'");
if (!isset($_GET['catt']) || $_GET['catt'] == '') {
unset($_GET['catt'], $_GET['submitsearchsub']);
populate_main();
} else {
if (isset($_GET['subcatt'])) {
echo '<span>Search results for Category="'.$catt.' And Sub Category='.$subcatt.'"</span><hr>';
}
$result = mysqli_query($link,"SELECT * FROM `item` WHERE cat='$catt' AND field='$subcatt'");
if ($cat = mysqli_fetch_row($result)) {
echo '
<div class="itemlist">
<span><h3>'.$cat[1].'</h3><h6><u>View</u></h6></span>
<div class="col-lg-12" style="background-color: white;"><br>
<div class="row">
<div class="col-lg-12" style="margin-right: 2%;">
<img src="https://via.placeholder.com/160x210">
</div>
</div><br>
</div>
</div>
<hr>
';
while ($cat = mysqli_fetch_row($result))
echo '
<div class="itemlist">
<span><h3 style="display:inline;">'.$cat[1].'</h3><h6 style="display:inline; margin-left: 1%;"><u>View</u></h6></span>
<div class="col-lg-12" style="background-color: white;"><br>
<div class="row">
<div class="col-lg-2" style="margin-right: 2%;">
<img src="https://via.placeholder.com/160x210">
</div>
</div><br>
</div>
</div>
<hr>
';
} else {
if (isset($_GET['subcatt'])) {
echo "<h2 >No results found</h2>";
}
unset($_GET['catt'], $_GET['submitsearchsub']);
populate_main();
}
}
}
First of all, grab $_GET['catt'] and $_GET['subcatt']. Then, you can build a query based on these parameters. And please, use mysqli_num_rows to check if there are more than zero rows returned.
function populate_search_catsub()
{
global $link;
$catt = $_GET['catt'] ?? ''; // Requires PHP 7.0 or upper.
$subcatt = $_GET['subcatt'] ?? ''; // Requires PHP 7.0 or upper.
$query = 'SELECT * FROM `item`'; // Initial query
if (!$catt) {
unset($_GET['submitsearchsub']);
populate_main();
} else {
$query .= " WHERE `cat` = '{$catt}'";
if ($subcatt) {
echo '<span>Search results for Category="' . $catt . ' And Sub Category=' . $subcatt . '"</span><hr>';
$query .= " AND `field` = '{$subcatt}'";
}
$result = mysqli_query($link, $query);
if (mysqli_num_rows($result) > 0) { // Check if result set is not empty.
while ($cat = mysqli_fetch_row($result))
echo '
<div class="itemlist">
<span><h3 style="display:inline;">'.$cat[1].'</h3><h6 style="display:inline; margin-left: 1%;"><u>View</u></h6></span>
<div class="col-lg-12" style="background-color: white;"><br>
<div class="row">
<div class="col-lg-2" style="margin-right: 2%;">
<img src="https://via.placeholder.com/160x210">
</div>
</div><br>
</div>
</div>
<hr>
';
} else {
if ($subcatt) {
echo '<h2 >No results found</h2>';
}
unset($_GET['catt'], $_GET['submitsearchsub']);
populate_main();
}
}
}

How to display the datas from two tables using search query?

I need to display datas from particular based on the results.
I have two tables movies_info => has all movies info & tv_shows_info => has TV shows info. I have search box if i enter the search it should search from both the table and display the datas but the condition in the results if it has movie_id, it should show movie details and if the result has tv_show_id it should show tv-show details.
as of now i have used basic search to fetch datas from one table and i have tried of using two but its not working.
<?php
// sql query for retrieving data from database
$sql_query = "SELECT * FROM `movies_info`";
$result = mysqli_query($connection, $sql_query);
// SQL Query for filter
if(isset($_POST['search_button']))
{
$value_to_search = $_POST['value_to_search'];
// search in all table columns
// using concat mysql function
$search_query = "SELECT * FROM `movies_info` WHERE CONCAT(`movie_name`, `movie_original_name`, `release_year`, `movie_genre`, `movie_country`, `movie_stars`, `movie_director`) LIKE '%".$value_to_search."%'";
//$search_query = "SELECT * FROM `movies_info`,`tv_shows_info` WHERE CONCAT(`movie_name`, `release_year`, `movie_genre`, `movie_country`, `tv_show_name`) LIKE '%".$value_to_search."%' GROUP BY `movie_id`";
//$search_query = "SELECT * FROM `movies_info` UNION ALL `tv_shows_info` WHERE CONCAT(`movie_name`, `release_year`, `movie_genre`, `movie_country`, `tv_show_name`) LIKE '%".$value_to_search."%'";
//$search_query2 = "SELECT * FROM `tv_shows_info` WHERE CONCAT(`tv_show_name`, `tv_show_start_year`, `tv_show_end_year`, `tv_show_genre`, `tv_show_country`) LIKE '%".$value_to_search."%'";
//$search_query .= $search_query2;
$search_result = filterTable($search_query);
}
else {
$search_query = "SELECT * FROM `movies_info`";
$search_result = filterTable($search_query);
//echo 'No Search Results Found';
}
?>
<!-- /w3l-medile-movies-grids -->
<div class="general-agileits-w3l">
<div class="w3l-medile-movies-grids">
<!-- /movie-browse-agile -->
<div class="movie-browse-agile">
<!--/browse-agile-w3ls -->
<div class="browse-agile-w3ls general-w3ls">
<div class="tittle-head">
<h4 class="latest-text">Search Results for : "<?php echo $value_to_search ?>"</h4>
<div class="container">
<div class="agileits-single-top">
<ol class="breadcrumb">
<li>Home</li>
<li class="active" style="text-transform:Capitalize;">Search Results </li>
</ol>
</div>
</div>
</div>
<div class="container">
<div class="browse-inner">
<?php
echo $search_result;
$rowcount = mysqli_num_rows($search_result);
for($i=1;$i<=$rowcount;$i++){
$row=mysqli_fetch_array($search_result);
?>
<div class="col-md-2 w3l-movie-gride-agile">
<a href="movie.php?movie_id=<?php echo $row['movie_id']; ?>" class="hvr-shutter-out-horizontal"><img src="<?php echo $row['movie_image']; ?>" title="<?php echo $row['movie_name']; ?>" alt=" " />
<div class="w3l-action-icon"><i class="fa fa-play-circle" aria-hidden="true"></i></div>
</a>
<div class="mid-1">
<div class="w3l-movie-text">
<h6><?php echo $row['movie_name']; ?></h6>
</div>
<div class="mid-2">
<p><?php echo $row['release_year']; ?></p>
<div class="block-stars">
<ul class="w3l-ratings">
<li>
<span>IMDB <i class="fa fa-star" aria-hidden="true"></i> <?php echo $row['movie_rating']; ?> </span>
</li>
</ul>
</div>
<div class="clearfix"></div>
</div>
</div>
<div class="ribben two">
<p>NEW</p>
</div>
</div> <?php } ?>
</div>
as of now i can get the values from one table.,
My exact need is it can be Movie or TV-Show but i should get the datas from both the table if it is a movie it should show some particular info and if thats a TV-show it should show someother info.
First, you need to use prepared statements which you can use even if you are using the LIKE function in MySQL. Then you need to add spaces between the column names to prevent the values from being blended together like "star warsstar wars". This will cause a movie like "star wars to be a result when a user searches for "ss" which would be inaccurate.
$search_result = array();
$search_query = "SELECT * FROM `movies_info` WHERE CONCAT(`movie_name`,' ', `movie_original_name`,' ',`release_year`,' ',`movie_genre`,' ',`movie_country`,' ',`movie_stars`,' ',`movie_director`) LIKE CONCAT('%',?,'%')";
if($stmt = $db->prepare($search_query)){
$stmt->bind_param('ii',$_SESSION['iidn_reference'],$o['parent_ref_id']);
if($stmt and $stmt->execute()){
$result = $stmt->get_result();
while($row = $result->fetch_array(MYSQLI_ASSOC)){
$search_result[] = $row;
}
}
}
After that, you could combine these tables with MySQL UNION but I strongly recommend just searching both tables and aliasing the table names to match.
SELECT 'movie' as `type`, `movie_id` as `id`, `movie_name` as `name`...
SELECT 'show' as `type`, `show_id` as `id`, `show_name` as `name`...

I need help displaying data in php

I am just learning php and I have a problem with a project. I have a database in mysql (localhost) and in it I have 3 tables: categories, products and restaurants, categories and restaurants are linked to products. And when I try to display products of a specified category it doesn't display anything. The connection to the database is good and the queries are good so I have no idea what's wrong. Pleas help.
This is the index.php
<?php
include_once './database.php';
include_once './header.php';
<div class="content" align="center">
<div id="galery" class="content_block" style="height:400px;">
<div class="galery">
<img src="./img/gallery/6.jpg">
</div>
</div>
<div class="content_block" style="padding-bottom:10px;">
$query = "SELECT * FROM categories";
$result = mysqli_query($link, $query);
while ($row = mysqli_fetch_array($result)){
echo '<div class="contentButton inline"><div class="catFood_img foodCategory_1"></div><div>'.$row['category'].'</div></div>';
</div>
<div class="content_block" style="height:190px" align="center">
$query = "SELECT * FROM restourants";
$result = mysqli_query($link, $query);
while ($row = mysqli_fetch_array($result)){
echo '<div class="restournats inline"><img src="./food/restourants/chens.jpg"></div>';
}
</div>
</div>
include_once './footer.php';
?>
And this is the code for categories.php
include_once './database.php';
include_once './header.php';
<div class="content" align="center">
<div class="content_block2">
$category= (int)(isset($_GET['id_category']) ? $_GET['id_category'] : '');
$query = "SELECT * FROM products WHERE products.id_category=$category";
$result = mysqli_query($link, $query);
while($row = mysqli_fetch_array($result)){
echo '
<a href="dishes.php?id='.$row['id'].'"><div class="item inline">
<div class="food_img"><img src="'.$row['img'].'" /></div>
<div class="title">'.$row['name'].'</div>
<div class="price inline">Price: '.$row['price'].' €</div><div class="btn">Choose</div>
</div>
</a>';
}
</div>
</div>
include_once './footer.php';
In your index.php you are creating the link as
echo '<a href="categories.php?cat='.$row['category'].'">
(double check $row['category'] given above is the desired category id value you need)
But in your categories.php you are trying to get the category as
$category= (int)(isset($_GET['id_category']) ? $_GET['id_category'] : '');
Try $_GET['cat'] instead of $_GET['id_category']
Also try echo $category and echo $query to see if you are getting the desired values.

PHP if mysqli query statement

I am in the process of creating a website that displays a group of questions, however my problem is checking if the user has answered the question or not, and if they have, display an “Answered” label.
However the currently, It is displayed the “Answered” Label for each and every question, even if the answer is not in the submissions table. Any help would be appreciated.
while($data = mysqli_fetch_row($result)){
if($data[0] != null){
echo('
<div class="col-md-4 col-sm-5">
<div class="panel panel-default text-center">
<div class="panel-heading">
<span class="fa-stack fa-5x">
<i class="fa fa-circle fa-stack-2x text-default"></i>
<i class="fa fa-codepen fa-stack-1x fa-inverse"></i>
</span>
</div>
<div class="panel-body">
');
if($result4 = mysqli_query($mysqli,"SELECT * FROM submissions where teamID='$teamName' and questionID='$data[0]' and status='correct'")){
echo "Answered";
} else{
echo "Not Answered";
}
echo ('
<h4>'.$data[6].' - <small><i>'.$data[8].' points</i></small></h4>
<p>'.$data[7].'</p>
View Question
</div>
</div>
</div>
');} else{
echo "No More Questions";
}
}
I know I am making a basic or stupid error here, So any help appreciated.
//Mysql query to find number of answers for particular question.
$answercount = mysqli_query($mysqli, "SELECT * FROM submissions where teamID='$teamName' and questionID='$data[0]' and status='correct'");
$answercount = mysqli_num_rows($answercount);
//PHP code
if($answercount>0){
echo "Answered";
} else{
echo "Not Answered";
}
you forget mysqli_query("")
if ($result4 = mysqli_query($con, "SELECT * FROM submissions where teamID='$teamName' and questionID='$data[0]' and status='correct'")) {
echo "Answered";
} else {
echo "Not Answered";
}

Categories