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();
}
}
}
Related
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} " : ""));
}
I have an array of objects in which I want to iterate them in a foreach loop. However I want to only allow for 3 of them to be in a row and then after the 3rd, a new row to start, and so on.
function displayIncomeDetails($deets) {
$result = NULL;
if($deets != NULL) {
foreach($deets as $deet) {
$result .= '
<div class="row mt-4">
<div class="col-sm-3">
'.$deet.'
</div>
</div>
';
}
} else {
$result = '
<div class="row">
<p style="margin: 0 auto;" class="mt-4 text-danger">No Details Found</p>
</div>
';
}
return $result;
}
So instead of 1 column in the row I would like 3
array_chunk is very usable here, e.g.:
foreach (array_chunk($deets, 3) as $perRow) {
$result .= '<div class="row mt-4">';
foreach ($perRow as $deet) {
$result .= '<div class="col-sm-3">' . $deet . '</div>';
}
$result .= '</div>';
}
I have used foreach loop to display the rows in myphp database, however I would now like to display this in DESC order (display last row first) however research tells me not to use the SELECT command in arrays? is there another way? Many thanks.
index.php:
<?php
include("app/database/db.php");
$posts = selectAll('posts', ['published' => 1]);
?>
<?php foreach ($posts as $post): ?>
<div class="post">
<div class="col-lg-6">
<!-- HEADLINE -->
<h1><strong><?php echo $post['title']; ?></strong></h1>
<!-- TEXT BODY -->
<!-- <h4></?php echo $post['body']; ?></h4> displays the full body -->
<h4 class="mainbody"><?php echo html_entity_decode(substr($post['body'], 0, 100) . '...'); ?></h4>
<!-- IMAGE -->
<div class="col-lg-6">
<img src="<?php echo '/assets/images/' , $post['image']; ?>" style="width: 550px; height: 350px; object-fit: cover;">
</div>
</div>
<?php endforeach; ?>
db.php file:
<?php
function selectAll($table, $conditions = []) {
global $conn;
$sql = "SELECT * FROM $table";
if (empty($conditions)) {
$stmt = $conn->prepare($sql);
$stmt->execute();
$records = $stmt->get_result()->fetch_all(MYSQLI_ASSOC);
return $records;
} else {
$i = 0;
foreach ($conditions as $key => $value) {
if ($i === 0) {
$sql = $sql . " WHERE $key=?";
} else {
$sql = $sql . " AND $key=?";
}
$i++;
}
$stmt = executeQuery($sql, $conditions);
$records = $stmt->get_result()->fetch_all(MYSQLI_ASSOC);
return $records;
}
}
?>
PHP enthusiast here..
I have a script where it does a query and brings the entire database rows into table cells and it's paginated.
The problem is when a user types something in the search box to filter the pagination, it only works in page 1 showing the filtered results but then it stops working on page 2, on page 2 is goes back to all the paginated results and ignores the filter.
How do I bring the filter value into the url so it stays throughout the pagination?
Sorry if it's obvious I just can't figure it out
<?php require('includes/config.php');
//if not logged in redirect to login page
if(!$user->is_logged_in()){ header('Location: index.php'); exit(); }
//include header template
require('layout/header.php');
$stmt = $db->query("SELECT name, last_name FROM `designers` WHERE `username` = '" . $_SESSION['username'] . "'");
$result1 = $stmt->fetch(PDO::FETCH_ASSOC);
$name = $result1['name'];
$last_name = $result1['last_name'];
if (isset($_GET['pageno'])) {
$pageno = $_GET['pageno'];
} else {
$pageno = 1;
}
$no_of_records_per_page = 15;
$offset = ($pageno-1) * $no_of_records_per_page;
$conn=mysqli_connect("xxxx", "xxxx", "xxxx", "xxxx");
$total_pages_sql = "SELECT COUNT(*) FROM protonumbers WHERE designer LIKE '".$name.'_'.$last_name."'";
$result = mysqli_query($conn,$total_pages_sql);
$total_rows = mysqli_fetch_array($result)[0];
$total_pages = ceil($total_rows / $no_of_records_per_page);
?>
<style>
table {
border-collapse: collapse;
width: 100%;
}
th, td {
text-align: center;
padding: 8px;
}
tr:nth-child(even){background-color: #f2f2f2}
th {
background-color: #428bca;
color: white;
}
</style>
<div class="container">
<div class="row">
<div class="col-xs-12 col-sm-8 col-md-6 col-sm-offset-2 col-md-offset-3">
<form action="search.php" autocomplete="off" method="post">
<h3>My Proto Numbers</h3><hr><br>
<?php
//check for any errors
if(isset($error)){
foreach($error as $error){
echo '<p class="bg-danger">'.$error.'</p>';
}
}
?>
</div>
</div>
</div>
<?php
if(isset($_POST['search']))
{
$valueToSearch = $_POST['valueToSearch'];
// search in all table columns
// using concat mysql function
$query = "SELECT * FROM `protonumbers` WHERE UPPER(CONCAT(`brand`, `protoID`, `season`, `program`, `protonumber`)) LIKE UPPER('%".$valueToSearch."%') AND designer LIKE '".$name.'_'.$last_name."' LIMIT $offset, $no_of_records_per_page";
$search_result = filterTable($query);
}
else {
$query = "SELECT * FROM `protonumbers` WHERE designer LIKE '".$name.'_'.$last_name."' LIMIT $offset, $no_of_records_per_page";
$search_result = filterTable($query);
}
// function to connect and execute the query
function filterTable($query)
{
$connect = mysqli_connect("xxxx", "xxxx", "xxxx", "xxxx");
$filter_Result = mysqli_query($connect, $query);
return $filter_Result;
}
?>
<div class="container">
<div class="row">
<div class="col-xs-12 col-sm-8 col-md-6 col-sm-offset-2 col-md-offset-3">
<div class="form-group">
<input type="text" name="valueToSearch" class="form-control input-lg" placeholder="Search by Proto number, Season, Brand, Program" tabindex="1">
<div class="row"><br />
<div class="col-xs-6 col-md-6">
<input type="submit" name="search" value="Search" class="btn btn-primary btn-block btn-lg" tabindex="2"> .
</form></div></div></div></div>
<div class="col-xs-12 col-sm-8 col-md-6 col-sm-offset-2 col-md-offset-3">
Back<br><br> <ul class="pagination">
<li>First</li>
<li class="<?php if($pageno <= 1){ echo 'disabled'; } ?>">
Prev
</li>
<li class="<?php if($pageno >= $total_pages){ echo 'disabled'; } ?>">
<a href="<?php if($pageno >= $total_pages){ echo '#'; }
else { echo "?pageno=".($pageno + 1); } ?>">Next</a>
</li>
<li>Last</li>
</ul>
<table>
<tr>
<th>ProtoID</th>
<th>Brand</th>
<th>Season</th>
<th>Program</th>
<th>Proto Number</th>
</tr>
<!-- populate table from mysql database -->
<?php while($row =
mysqli_fetch_array($search_result)):?>
<tr>
<td><?php echo $row['protoID'];?></td>
<td><?php echo $row['brand'];?></td>
<td><?php echo $row['season'];?></td>
<td><?php echo $row['program'];?></td>
<td><?php echo $row['protonumber'];?></td>
</tr>
<?php endwhile;?>
</table>
</div></div>
<?php
//include header template
require('layout/footer.php');
?>
Ok, so, as stated in the comments this boils down to HTTP not being stateful, you'll need to persist those filters values across requests. So, storing things in say session, or simply keeping the URIs query string in state.
So building out that query string...
<?php
$assignedFilters = [];
if (!empty($name)) $assignedFilters['name'] = $name;
if (!empty($last_name)) $assignedFilters['last_name'] = $last_name;
$filterParams = http_build_query($assignedFilters);
?>
And then getting it on the href for you pagination links... Here is one example
<a href="<?php if($pageno <= 1) { echo '#';
} else {
echo "?pageno=".($pageno - 1) . '&' . $filterParams; } ?>">Prev</a>
In other words append . '&' . $filterParams to your existing pagination links.
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;
}