PHP get total in multiple loop - php

I am using the following script where in I want the total projects of a particular branch, the tables are as follows --
Tbl_branch has -
Branch Id |
Branch Name
Tbl_employee has -
emp_id |
bid (branch id ) |
emp_details
Tbl_Project has -
id | project_details | emp_id(which employee added the project)
--
Here I want to get total projects of a particular branch where in the user will select the branch name through a dropdown and its id will be in the value.
I am using the following query
<?php
$result1 = mysql_query("select * from tbl_employee WHERE bid = '$bid'");
while ($row1 = mysql_fetch_array($result1)){
$eid = $row1['id'];
$pro = mysql_query("SELECT COUNT(id) FROM tbl_project WHERE emp_id = '$eid'") or die(mysql_error());
$rowpro = mysql_fetch_array($pro);
$totalprojectsb = $rowpro[0];
?>
<div class="card-container col-lg-3 col-md-6 col-sm-12">
<div class="card card-red hover">
<div class="front">
<h1>Total Enquires</h1>
<p id="users-count"><?php echo $totalprojectsb; ?></p>
<span class="fa-stack fa-2x pull-right">
<i class="fa fa-circle fa-stack-2x"></i>
<i class="fa fa-user fa-stack-1x"></i>
<span class="easypiechart" data-percent="100" data-line-width="4" data-size="80" data-line-cap="butt" data-animate="2000" data-target="#users-count" data-update="3000" data-bar-color="white" data-scale-color="false" data-track-color="rgba(0, 0, 0, 0.15)"></span>
</span>
</div>
<div class="back">
<ul class="inline divided">
<li>
<h1>Total Projects </h1>
<p><?php echo $totalprojectsb; ?></p>
</li>
<li>
<h1>This Month</h1>
<p><?php ?></p>
</li>
</ul>
<div class="summary negative"> <i class="fa fa-arrow-down"></i> </div>
</div>
</div>
<?php } ?>
This shows the total tile as many times as the total number of employees in that branch.
All I want here is to show one tile which will get the total number of projects from one particular branch.
I saw somewhere array could be used for such things but I am not sure how.
Please help. Also correct my question if not properly framed.

Well, as long as you are interested only in total number of project on particular branch, you could just change your SQL as follows:
SELECT COUNT(id)
FROM Tbl_Project
WHERE emp_id IN (
SELECT emp_id
FROM Tbl_employee
WHERE bid = '$bid'
)
This query should return total number of project on selected branch
Edit: to clarify a bit: The inner SELECT selects all employee which are working on that branch, the outer SELECT select all project, that was created by employees selected in inner SELECT (eg. project on that branch). The COUNT only count such projects.

You're expecting the following: "Here I want to get total projects of a particular branch where in the user will select the branch name through a dropdown and its id will be in the value." -> That is, irrelevant of which user is currently logged in, or whose projects it is, you want to classify them based on the branch they are associated with (through the various employees who belong to a given branch and have created the project).
SELECT b.branchid, b.branchname, count(p.projectid) AS branchProjects FROM tbl_employee AS e
LEFT JOIN tbl_project AS p ON p.empid = e.empid
LEFT JOIN tbl_branch AS b ON b.branchid = e.bid
GROUP BY b.branchid
With the above SQL, you will be connecting your tables and grouping the received data by the branchID, and counting the results which are connected to them.

Related

PHP MYSQL how to show and list all records from two tables using current table's record id?

I have two tables "naujienos" and "apzvalgos" in my SQL Database. I managed to join them both and get all records from both tables using UNION and ORDER BY timestamp. What i need to do is to match records id by current id to show particular record on webpage.
Here is my code :
<?php
$sql="Select * from `naujienos` UNION Select * from `apzvalgos` order by `timestamp` DESC";
$result=mysqli_query($con,$sql);
if($result){
while($row=mysqli_fetch_assoc($result)){
$id=$row['topic_id'];
$topic_image=$row['topic_image'];
$topic_name=$row['topic_name'];
$topic_desc=$row['topic_desc'];
$timeStamp=$row['timeStamp'];
$kategorija=$row['kategorija'];
echo '<div class="card-group pl-5 col-md-3 col-sm-6 mb-5 pb-5">
<div class="card">
<img class="card-img-top paveiksliukas" src='. $topic_image.' alt="Card image cap">
<div class="card-body">
<h5 class="card-title mb-5">'. $topic_name.'</h4>
<p class="card-text">'.substr($topic_desc,0,200).'</p>
Skaityti toliau
</div>
<div class="text-center">
<b>Kategorija: '. $kategorija. '</b>
</div>
<div class="text-center pt-1 pb-1">
<b>Įkelta: '. $timeStamp. '</b>
</div>
</div>
</div>';
}
}
?>
Here is how it looks on webpage (its basically all records from two tables and whenever i click on button i go to that particular record):
This is the code line where when i click on button i get to that particular record by id :
Skaityti toliau
My problem is that when i click on "apzvalgos" table button it sends me to "naujienos" table record, because ive written this:
Skaityti toliau
Right now its only working with "naujienos" records and when i click on "apzvalgos" record it shows me "naujienos" record instead.
Both tables have identical columns.
How can i change the code that when i click on records from "naujienos" and "apzvalgos" table's it shows current record from those two tables?
I've tried to change the code line
Skaityti toliau
to somehow get current table record's id, but i have no idea how to do it.
Can someone help me to fix this problem?
Skaityti toliau
//on naujienos.php file
$id1 = REQUEST['naujienos_id'];
//Show record
$sql = "SELECT * FROM naujienos INNER JOIN apzvalgos ON naujienos.naujienos_id=apzvalgos.apzvalgos_id WHERE naujienos_id='$id1'";
//your code here

Trouble getting a category when including a topic in a page in PHP

I'm stuck on a query.
My goal is to get the information of that data and all the information belonging to the category of that data in a single query.
I have a usable code but the function is faulty. The error is that how many categories there are, the same data as the number of categories.
rotate
My fault: https://prnt.sc/OzPLaGHFMGP5
My table where I store my data: https://prnt.sc/PEqSq2mM5NKM
My table where I keep my categories: https://prnt.sc/WK7n8kAGoUWD
here is my code to pull my data into the page:
if (!isset($_GET['url']) || empty($_GET['url'])){
header('Location:404.php');
}
$datas = $db->prepare('SELECT * FROM post WHERE url = ?');
$datas->execute([
$_GET['url']
]);
$data = $data->fetch(PDO::FETCH_ASSOC);
if (!$data){
header('Location:404.php');
exit;
}
here is my code where I pull the data category:
<?php $categories = $db->query('SELECT Categories.*, COUNT(posts.id) as totalCategory FROM categories
LEFT JOIN posts ON FIND_IN_SET(categories.id, posts.category_id)
GROUP BY Category.id DESC')->fetchAll(PDO::FETCH_ASSOC); ?>
<?php foreach ($category as $category): ?>
<div class="container mt-4">
<div class="row">
<div class="col-md-12">
<div class="card mb-3">
<div class="card title">
<i class="bi-folder"></i> Category: <?=$category[ ' category_name']?>
<a class="Date"><?=$data['date']?> <i class="bi-clock"></i></a>
</div>
<div class="card body">
<?=htmlspecialchars_decode($data['content'])?>
</div>
</div>
</div>
</div>
<?php endforeach; ?>
So what is wrong with my query, what would you suggest?
So assuming your tables are called "categories" and "posts".
Based upon what you've currently given me within your question, i made the following query:
SELECT
categories.*,
COUNT(`posts`.`id`) AS `totalPosts`
FROM `categories`
LEFT JOIN `posts` ON `posts`.`category_id` = `categories`.`id`
ORDER BY `categories`.`id` DESC
It basically gets everything from categories and a count of how many posts are within that category. Then we do a left join to get the information that corresponds to the category id, and then we descend it based upon category id DESC (so going downwards).
Correct me if i'm mistaken in what you were asking

problem in joining 3 tables using INNER JOIN statement

I am trying to set a sql query that will show jobs from a selected type of trade and within certain distance. I have three tables clients, traders and jobs. What I need is like-
SELECT * from jobs WHERE the type of job required matches by the type of jobs this trader offers AND the DISTANCE between the client and trader is within a range specified
I have managed to get the first part done. it shows all jobs that match the types of job a trader offers, but struggling to get the second part. Here is my query
$stmt=$pdo->prepare("SELECT jobs.*, clientPostcode, traderPostcode FROM jobs
INNER JOIN traders ON FIND_IN_SET(jobs.tradeType,traders.tradeTypes ) WHERE traders.traderEmail=:traderEmail
INNER JOIN clients ON jobs.clientEmail= clients.clientEmail" );
$stmt->bindparam('traderEmail',$traderEmail);
$stmt->execute();
while($row=$stmt->fetch(PDO::FETCH_ASSOC)){
//calculate distance between origin and destination
IF (condition is ok){
?>
<div class="card col-lg-12 mt-5 text-center">
<div class="card-body">
<h6 class="card-title text-primary">Job Type: <?php echo $row['tradeType'] ?> (Job Title: <?php echo $row['jobTitle'] ?> ) </h6>
<p class="card-text"><?php echo $row['jobDescription'] ?></p>
<a class="btn btn-primary" href="">
<i class="fas fa-edit fa-xs"></i> Send Interest</a>
<a class="btn btn-success" href="" target="_blank">
<i class="fas fa-glasses fa-xs"></i> Shortlist</a>
</div>
</div>
<?php
}
}
?>
$stmt=$pdo->prepare("SELECT jobs.*, clients.clientPostcode, traders.traderPostcode FROM jobs
INNER JOIN traders ON FIND_IN_SET(jobs.tradeType,traders.tradeTypes )
INNER JOIN clients ON jobs.clientEmail= clients.clientEmail WHERE traders.traderEmail=:traderEmail " );
$stmt->bindparam('traderEmail',$traderEmail);
$stmt->execute();
while($row=$stmt->fetch(PDO::FETCH_ASSOC)){
$origin = $row['traderPostcode'];
$destination = $row['clientPostcode'];
then I used google distance matrix api (cURL)to calculate distance between the two postcodes. I appreciate everyone for your time. Will try to be more specific for future questions.

i want to count record from the table by foreign key

This is the shopping cart dropdown. I have made for my e-commerce store. Now I want if both the products in the cart Table have the same category Id in the table then I want to show a single product with a quantity of two. for example (2 * $240) .
this is the database table picture.
And this is the code for showing the products in the dropdown.
<ul class="header-cart-wrapitem">
<?php
$displayCart = "SELECT cart.*,products.product_img1 FROM `cart`
join products on products.product_id = cart.product_id
WHERE cart.status = 'enabled' order by cart.cart_id DESC";
$resultCart = mysqli_query($conn,$displayCart);
while($rowCart = mysqli_fetch_array($resultCart)){?>
<li class="header-cart-item">
<div class="header-cart-item-img">
<img src="<?=$base_url .'pages/Ajax/'.$rowCart['product_img1'];?>" alt="IMG">
</div>
<div class="header-cart-item-txt">
<a href="#" class="header-cart-item-name">
<?=$rowCart['product_name'];?>
</a>
<span class="header-cart-item-info">
<?=$rowCart['product_qty'];?> x $<?=$rowCart['product_price'];?>
</span>
</div>
</li>
<?php } ?>
</ul>
Something like this should do the trick!
SELECT
COUNT(product_id) as count,
cart.*,
products.product_img1
FROM
`cart`
join products on products.product_id = cart.product_id
WHERE
cart.status = 'enabled'
GROUP BY
product_id
order by
cart.cart_id DESC
Hope this helps!

Return Value in Column B Table 2, where column A Table 1, matches Column A Table 2

What I'm trying to do: Where category (projects) matches id (markets) echo category (markets).
Table 1 Sample (projects table)
Table 2 Sample (markets table)
Sample of PHP Code
$num_rec_per_page=5;
if (isset($_GET["page"])) { $page = $_GET["page"]; } else { $page=1; };
$start_from = ($page-1) * $num_rec_per_page;
function GET($key) {
return isset($_GET[$key]) ? $_GET[$key] : null;
}
$category= GET('category');
if ($category !== null) {
$sql = "SELECT * FROM projects WHERE category='$category' LIMIT $start_from, $num_rec_per_page";
} else {
$sql = "SELECT * FROM projects LIMIT $start_from, $num_rec_per_page";
}
$sql_query = mysql_query($sql);
$post = $sql_query;
$sql1 = "SELECT * FROM markets";
$sql_query1 = mysql_query($sql1);
$marketsinfo = mysql_fetch_array($sql_query1);
In my code below, I've tried putting a while loop within the main while loop since we have to find out what category its in then display it for each blog post.
It only worked for the first result, and then I did some research online and found that it is very poor design to do this.
Where I'm currently at with displaying the result (see code in between hyphens):
<!-- Blog - Start -->
<?php while ($post = mysql_fetch_array($sql_query)) {?>
<div class="col-lg-12 col-md-12 col-sm-12 col-xs-12 blog blog_altered blog_left">
<div class="row">
<!-- Blog Image - Start -->
<div class=" col-lg-6 col-md-6 col-sm-10 col-xs-12 pic inviewport animated delay1" data-effect="fadeIn">
<img alt="blog-image" class="img-responsive" src="<?php echo $post['imageoutside'] ?>">
</div>
<!-- Blog Image - End -->
<!-- Blog Info - Start -->
<div class="col-lg-6 col-md-6 col-sm-12 col-xs-12 inviewport animated delay1" data-effect="fadeIn">
<div class="info">
----------------------------------------------------------------------
<span class="date">
<?php
if($post['category'] === $marketsinfo['id']){
echo $marketsinfo['category'];
}
?>
</span>
----------------------------------------------------------------------
<h4 class="title"><?php echo $post['title'] ?></h4>
<p><?php echo $post['summary'] ?></p>
<a class="btn btn-primary text-on-primary" href="projects/readmore.php?job=<?php echo $post['job'] ?>">Read More</a>
</div>
</div>
<!-- Blog Info - End -->
</div>
</div>
<?php } ?>
<!-- Blog - End -->
Hope I've been thorough enough without being confusing. How can a noob accomplish this? I'll take any pointers you have!!
If you use a join, you can get the category text in one query and avoid all the looping in PHP.
A LEFT Join will return all records from Projects and only those records which match from markets. So if a projects category doesn't exist in markets, a NULL value will be returned.
If you used a INNER JOIN, only records which have corresponding values in BOTH tables would be returned.
Rule of thumb: get the data you need from the database in 1 trip when you need it. Format in PHP, Datagrab in SQL. Don't get more than you need, and don't get less.
SELECT P.Job, M.ID as Markets_ID, M.Category, P.Title
FROM projects P
LEFT JOIN Markets M
on P.Category =M.ID
WHERE P.category='$category'
LIMIT $start_from, $num_rec_per_page"
Note: you will need to put a table alias on category in the where clause. I'm assuming your passing in the ID so P.Category was used.
do you want join table projects with tables market by category?
may be u can do this
SELECT p.id as id
, m.category as category
from projects as p
left
join markets as m
on p.category = m.id
WHERE m.category='$category'
LIMIT $start_from
, $num_rec_per_page

Categories