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.
Related
I have facing big problem to auto count previous 6 months annoucement record in SQL put in the separate box. Is using loop to count the annoucement record? Anyone can guide me or give me an example to do it? If can, better using my code to edit and let me refer. Thanks a lot.
Below is my coding:
<?php
$sql_select = 'SELECT * FROM announcement where id = 20' ; //This I try to test id = 20 announcment to call out data
$query_select = db_conn_select($sql_select);
foreach ($query_select as $rs_select) {
$title = $rs_select['title'];
$date = $rs_select['posted_date'];
$contents = $rs_select['contents'];
}
?>
<div class="row">
<div class="col-md-12">
<div class="box box-success box-solid">
<div class="box-header with-border" style="text-align: center;" >
<h3 class="box-title" ><?php echo $title ?> (<?php echo $date ?>)</h3>
<div class="box-tools pull-right">
<button type="button" class="btn btn-default btn-xs collapse-box" data-toggle="collapse" data-target="#collapseExample1" aria-expanded="false" aria-controls="collapseExample"><i class="fa fa-minus"></i></button>
</div>
</div>
<div id="collapseExample1" class="collapse" style="overflow: auto; text-align: center;">
<?php echo $contents ?>
</div>
</div>
</div>
</div>
Below is my database information (I want get the posted_date previous 6 months annoucement record to show):
My coding output show like the below:
Actually I want the output like below show auto count previous 6 months announcements put in the separate box :
There are two problems:
1) Your query will only return one record. You need to change it so it fetches a set of records from the last 6 months.
The general pattern for finding the last 6 months is easy to find online
yourdatecolumn >= CURDATE() - INTERVAL 6 MONTH
(credit to this answer specifically in this case, but there are dozens of examples available). N.B. You didn't specify, but I'm assuming your DBMS is MySQL, since that's most commonly used with PHP. If you have a different DBMS, you can find an equivalent answer online with a few seconds of searching.
2) you're ending your loop too soon. The current code is ok for one record, but will fail when there is more than one. It will loop over all the records, but then keep assigning their values the same variables, so after the loop finishes you end up with just the last record's values inside those variables. And you are not using a loop to create the HTML multiple times.
To fix that, just bring the HTML inside the loop. Here's the final version:
<?php
$sql_select = 'SELECT * FROM announcement where posted_date >= CURDATE() - INTERVAL 6 MONTH';
$query_select = db_conn_select($sql_select);
foreach ($query_select as $rs_select) {
$title = $rs_select['title'];
$date = $rs_select['posted_date'];
$contents = $rs_select['contents'];
?>
<div class="row">
<div class="col-md-12">
<div class="box box-success box-solid">
<div class="box-header with-border" style="text-align: center;">
<h3 class="box-title">
<?php echo $title ?> (
<?php echo $date ?>)</h3>
<div class="box-tools pull-right">
<button type="button" class="btn btn-default btn-xs collapse-box" data-toggle="collapse" data-target="#collapseExample1" aria-expanded="false" aria-controls="collapseExample"><i class="fa fa-minus"></i></button>
</div>
</div>
<div id="collapseExample1" class="collapse" style="overflow: auto; text-align: center;">
<?php echo $contents ?>
</div>
</div>
</div>
</div>
<?php
}
?>
That way it will create the same HTML repeatedly for each record, and use the current values of your variables within each version.
I have 3 tables: "Terceiros", "Morada_Terceiro" and " Contactos_Terceiros". What i want to do is, when a client(=terceiro) is inserted is attributed to it an address (=table Morada_Terceiro) and contacts(=table Contactos_Terceiros). The problem is, I tried INNER JOIN and when i added more than one address or contact for the same person it wouldn't list, so i tried LEFT JOIN and it showed the same client twice, but with the same information, then i tried RIGHT,FULL JOIN and none of them worked
//Tabela Terceiros
$sql="SELECT Terceiros.*, Email, Telefone, Telemovel, TipoC, Morada, Localidade, CodPostal FROM ((Terceiros INNER JOIN Contactos_Terceiro on Terceiros.Numero = Contactos_Terceiro.Numero ) INNER JOIN Morada_Terceiro on Terceiros.Numero = Morada_Terceiro.Numero )";
if(isset($pesq))
$sql.=" where Nome like '$pesq' ";
$sql.=" limit $ini, $tp";
$res=$lig->query($sql);
//Tabela Contactos_Terceiro
$sql="SELECT Contactos_Terceiro.*, Nome FROM Contactos_Terceiro INNER JOIN Terceiros on (Terceiros.Numero = Contactos_Terceiro.Numero)";
if(isset($pesq))
$sql.=" where Nome like '$pesq'";
$sql.=" limit $ini, $tp";
$res=$lig->query($sql);
//Tabela Morada_Terceiro
$sql="SELECT Morada_Terceiro.*, Nome FROM Morada_Terceiro INNER JOIN Terceiros on (Terceiros.Numero = Morada_Terceiro.Numero)";
if(isset($pesq))
$sql.=" where Nome like '$pesq'";
$sql.=" limit $ini, $tp";
$res=$lig->query($sql);
// table Terceiros
$sql="SELECT * from Terceiros";
if(isset($pesq))
$sql.=" where Nome like '$pesq' ";
$sql.=" limit $ini, $tp";
$res=$lig->query($sql);
// the query for the button
<?php
$sql="SELECT Terceiros.*, Email, Telefone, Telemovel, TipoC, Morada, Localidade, CodPostal FROM ((Terceiros CROSS JOIN Contactos_Terceiro on Terceiros.Numero = Contactos_Terceiro.Numero ) CROSS JOIN Morada_Terceiro on Terceiros.Numero = Morada_Terceiro.Numero )";
$res=$lig->query($sql);
while ($lin=$res->fetch_array()){ ?>
<tr>
<td><?php echo$lin[Numero]; ?></td>
<td><?php echo$lin[Cliente]; ?></td>
<td><?php echo$lin[Fornecedor]; ?></td>
<td><?php echo$lin[NIF]; ?></td>
<td><?php echo$lin[Nome]; ?></td>
<td><?php echo$lin[Idsiliamb]; ?></td>
<td><?php echo$lin[Tipo]; ?></td>
<td><img src='Imagens/edit.png' width="20" height = "20" ></td>
<td><a href=index.php?cmd=delter&Numero=<?php echo$lin[Numero];?> title="Apagar" onclick="return confirm('Tem a certeza que deseja apagar este registo?');" ><img src='Imagens/delete.png' width="20" height = "20" ></a></td>
<td><button data-toggle = "modal" data-target = "#<?php echo$lin[Numero];?>" title="Visualizar" class="btn btn-default openBtn"><img src='Imagens/eye.png' width="20" height = "20" ><button></td>
</tr>
<!-- Inicio do PopUp -->
<div class="modal fade" id="<?php echo $lin['Numero']; ?>" tabindex="-1" role="dialog" aria-labelledby="myModalLabel">
<div class="modal-dialog" role="document">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">×</span></button>
<h4 class="modal-title text-center" id="myModalLabel"><?php echo $lin['Nome']; ?></h4>
</div>
<div class="modal-body">
<div class="table-responsive">
<div class="divTable blueTable">
<div class="divTableHeading">
<div class="divTableRow">
<div class="divTableHead">Telefone</div>
<div class="divTableHead">Telemovel</div>
<div class="divTableHead">Email</div>
<div class="divTableHead">Tipo</div>
<div class="divTableHead">Morada</div>
<div class="divTableHead">Localidade</div>
<div class="divTableHead">Codigo Postal</div>
</div>
</div>
<div class="divTableBody">
<div class="divTableRow">
<div class="divTableCell"><?php echo $lin['Telefone']; ?></div>
<div class="divTableCell"><?php echo $lin['Telemovel']; ?></div>
<div class="divTableCell"><?php echo $lin['Email']; ?></div>
<div class="divTableCell"><?php echo $lin['TipoC']; ?></div>
<div class="divTableCell"><?php echo $lin['Morada']; ?></div>
<div class="divTableCell"><?php echo $lin['Localidade']; ?></div>
<div class="divTableCell"><?php echo $lin['CodPostal']; ?></div>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
<!-- Fim do PopUp -->
<?php } ?>
</tbody>
</table>
From what I understand, when you tried
Terceiros INNER JOIN Contactos_Terceiro INNER JOIN Morada_Terceiro
there might not be data present in any one of these three tables and that is why you got empty result set.
LEFT JOIN in place of INNER JOIN is the best option to go with and I think you got the correct result trying that. Let's say you have two contact records C1, C2 for user U1, the LEFT JOIN would map U1 against both C1 and C2 and that's why you get U1 twice.
You can try the following steps:
1. Query only the Users (Terceiros) table without any JOINS for
displaying the first page with Eye button.
2. Once the user clicks the Eye button, shoot the query with LEFT JOIN for
the particular user and now you will get n records based on the
number of contacts present for the particular User using which you
can display the different contacts present for the User
I do not think it is doable. Let's say I am Alex, I have Mary and John as contacts and I have London and Bristol as my addresses. What recordset do you want returned?
Alex | Mary | London
Alex | John | London
Or
Alex | Mary | London
Alex | Mary | Bristol
I do not think it is what you want.
The addresses and contacts data sets seem to be unrelated. Whatever SQL you apply, you can only get their Cartesian product.
I think you need two recordsets displayed in two screen tables.
Basically, you second join should be something like
SELECT Terceiros.*, Email, Telefone, Telemovel, TipoC, Morada, Localidade, CodPostal
FROM Terceiros
INNER JOIN Contactos_Terceiro on Terceiros.Numero = Contactos_Terceiro.Numero
INNER JOIN Morada_Terceiro on Contactos_Terceiro.USE_CONTACT_ID_HERE = Morada_Terceiro.THIS_SHOULD_BE_CONTACT_ID_FIELD
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
I am selecting data from 3 tables using a two left joins.
This all works up until the iteration of one of the values for an association (i think, through process of elimination).
I now have reason to believe the select statement is incorrect at the point of the JOINs, but i cannot see how.
The join that is not functioning as expected:
LEFT JOIN
ae_template_pageTypes t ON t.ae_template_pageTypes_id = tp.ae_template_page_group_id
Here i am trying to get the ae_template_pageTypes_type_label by the ae_template_pageTypes_idassociation.
Table: ae_template_pages
Table: ae_template_pageTypes
Table: ae_template_groups
The HTML Output(Both showing HTML instead of using join respectively)
THE ISSUE
I am expecting 2 different values in the format section where here shows both as HTML. I cannot locate why this is happening.
The SELECT
SELECT tg.ae_template_group_name, tp.ae_template_page_id, tp.ae_template_page_group_id, tp.ae_template_page_title, tp.ae_template_page_type, tp.is_group_index, t.ae_template_pageTypes_id, t.ae_template_pageTypes_type_label
FROM
ae_template_pages tp
LEFT JOIN
ae_template_pageTypes t ON t.ae_template_pageTypes_id = tp.ae_template_page_group_id
LEFT JOIN
ae_template_groups tg ON tg.ae_template_group_id = tp.ae_template_page_group_id
WHERE tp.ae_template_page_group_id = '$tempGroup_id'
NOTE: I have tried all types of join to test without finding a solution.
The PHP
foreach ($template_pages as $key => $value) {
?>
<li class="dd-item dd3-item" data-id="<? echo $template_pages[$key]['ae_template_page_id']; ?>">
<div class="dd-handle dd3-handle"></div>
<div class="dd3-content ae_template_page" data-template_page_name='<? echo $template_pages[$key]['ae_template_page_title']; ?>' data-template_page_id='<? echo $template_pages[$key]['ae_template_page_id']; ?>'><? echo $template_pages[$key]['ae_template_page_title']; ?>
<span style='float: right;margin-top: -3px;'>
<div style="" class="btn-group">
<span class="btn-info btn-xs dropdown-toggle" data-toggle="dropdown" title="Click to change file type" type="button"><? echo $template_pages[$key]['ae_template_pageTypes_type_label']; ?></span>
<ul role="menu" class="dropdown-menu" data-page_id='<? echo $template_pages[$key]['ae_template_page_id']; ?>'>
<li>JS</li>
<li>HTML</li>
<li>CSS</li>
</ul>
<span class="btn-info btn-xs" title="This file belongs to Template Group: <? echo $template_pages[$key]['ae_template_group_name']; ?>" type="button"><? echo $template_pages[$key]['ae_template_group_name']; ?></span>
<?
if ($template_pages[$key]['is_group_index'] == 1) {
?>
<span class="btn-success btn-xs" title="This is the default file for this group" type="button">Group index</span>
<?
}
?>
</div>
</span>
</div>
</li>
<?
}
SQL workbench output using the above statement with the $tempGroupId set to 1
For this and future try and restructure your sql to make it clearer eg:
select * from (
(select * from table_a) tbla
left join
(select * from table_b) tblb
on tbla.commoncolname=tblb.commoncolname
)
Try this on the database tool first (eg SQL Workbench), then move on to what the php retrieves and so on to the html
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.