Excluding certain unique IDs and then grouping the remaining ones - php

So I'm building a car booking website. And there is a cars tables that is like this:
Cars
CarID
CarModel
CarMake
Registration
And also a reservations table like this:
Reservations:
ReservationID
CarID
StartDate
EndDate
So When a user inputs the dates which they would like to book a car I query my reservations table:
If the dates are already in the reservation table I want to get that car ID, and then exclude that car from the list the user is shown, so they can not book it.
My problem is that I have multiple cars in the Database that are the same mode and make but have a different CarID and Registration.
I also group the cars by model so that a user is only shown one car of a certain type.
$carstring = mysql_query("SELECT * FROM cars {$statement} AND deleted = 'no'" GROUP BY CarModel);
$getcars = $carstring;
while($searchcars = mysql_fetch_array($getcars)) {
$checkreservations = mysql_query("SELECT * FROM reservations WHERE startDate = '".$sqlcoldate."' and carID = '".$searchcars['carID']."'");
$thiscar_num_rows = mysql_num_rows($checkreservations);
So as you can see at the minute I can tell which cars are taken in the reservations table, and I can echo out true or false from the num_rows
However I think it is the wrong way around because what I want to do is find out which cars by CarID are already taken, and then exclude them from the $getcars query loop that displays all the cars to the user, then group by model.
Can anyone tell me a way to do this, or even a better way to go about it?

An easy way to exclude the cars that are reserved is awith a subquery that gets all cars that ARE reserved and than stating in the main query that those cars are not allowed with the CarID NOT IN construction
<?php
// select all cars that are not reserved at sqlcoldate
$sql = "SELECT *
FROM Cars
WHERE CarID NOT IN (
SELECT CarID
FROM Reservations
WHERE StartDate > '".$sqlcoldate."' and EndDate < '".$sqlcoldate."'
)
GROUP BY CarModel";
// execute that query
$result = mysql_query($sql);
// if there are no results print a message
if (mysql_num_rows($result) == 0) {
echo "No cars found";
exit; // Exit the function, because there is nothing to do
}
// else print all available cars
while ($row = mysql_fetch_assoc($result)) {
echo "Model available car is :" . $row["CarModel"] . " </br>";
}
?>

Didn't actualy test it. But it should work
SELECT c.* FROM cars c
LEFT JOIN reservations r
ON c.carID=r.carID AND
selected_date BETWEEN r.startDate AND r.endDate
WHERE r.carID is null

Related

How to list records by date?

you see I am trying to list the records of a table in my database, but I want to do it in the following way:
First, it has to display the date
and then all the records on that date should appear
In my table of the database I have 4 fields:
id, task, date, time
For example there are multiple tasks that are performed in a day, but at different times. Then I have stored in my database many tasks of different days and in different hours. What I want is to list them per day. Consult the database and show a list where the date appears first and then all the tasks that were done on that date, then show the other date and then all the tasks of that date and so on.
Something like that
That's my php code
$obj = new Task();
$consult = $obj->Lists();
date_default_timezone_set("America/Mexico_City");
$dateActual = date("Y-m-d");
while ($result = $consult->fetch_object()) {
echo "<button class='btn btn-default'>date = " . $result->date . "</button><br>";
$consult2 = $obj->Lists2($dateActual);
while($result2 = $consult2->fetch_object()) {
echo "<span>". $result2->time ."</span><br>";
}
$dateActual = $result->date;
}
my query to the database is:
public function Lists2($date)
{
global $conexion;
$sql = "SELECT ar.*, date_format(ar.date, '%d/%m/%Y') as date,
date_format(ar.time, '%r') as time,
u.user as User
FROM task_recents ar
INNER JOIN user u ON ar.iduser = u.iduser
WHERE date = '$date'
ORDER BY ar.time DESC";
$query = $conexion->query($sql);
return $query;
}
public function Lists()
{
global $conexion;
$sql = "SELECT ar.*, date_format(ar.date, '%d/%m/%Y') as date,
date_format(ar.time, '%r') as time,
u.user as User
FROM task_recents ar
INNER JOIN user u ON ar.iduser = u.iduser
ORDER BY ar.time DESC";
$query = $conexion->query($sql);
return $query;
}
The result is that it shows me the repeated date with their respective records.
What I'm trying to achieve is something like this:
How could I do it?
PD: The result that I'm getting is this:
But I don't like that...
The INNER JOIN keyword selects all rows from both tables as long as there is a match between the columns. If there are records in the "Orders" table that do not have matches in "Customers", these orders will not be shown!
The following query should no longer generate duplicate records
SELECT
ar.id,
ar.task,
date_format(ar.date, '%d/%m/%Y') as formattedDate,
date_format(ar.time, '%r') as formattedTime,
u.user as User
FROM
task_recents ar
LEFT JOIN
user u
ON
u.iduser = ar.iduser
WHERE
date = '$date'
ORDER BY
ar.time
DESC

Sql search from 2 or 3 table

I have a search form where I can search for my webshop products.
1 product can be in multiple categoris, not just in one. I store this in the termek_katgoria_kapcsolo table. At insert, it creates as many lines, as the product belong to many categoria.
Example: The ID 12 product belong to ID 1, ID 2, ID 3 categoria.
The search sql only look at categoria, when one categoria is selected. Most often, I just search for the products name, I don't sort it to categoris.
How can I write the sql, that if I select a categoria also? I show you the tables on a pic.
if($termek_kategoria == 0 ) // Sort to categoria or not only search for product name, id...
{
$sql = "
SELECT termek_id, termek_nev, termek_cikkszam, termek_status FROM termek
WHERE $kereses_helye LIKE '%$kw%' ORDER BY $kereses_rendezes $kereses_sorrend
";
}
else
{
// Sorting for categoria also
$sql = "
SELECT termek_id, termek_nev, termek_cikkszam, termek_status FROM termek
WHERE $kereses_helye LIKE '%$kw%' AND termek_kategoria =
'$termek_kategoria' ORDER BY $kereses_rendezes $kereses_sorrend
";
}
Update:
$sql = "
SELECT termek.termek_id, termek.termek_nev, termek.termek_cikkszam, termek.termek_status
termek_kategoria_kapcsolo.*, termek_kategoria.kat_id
FROM termek
LEFT JOIN termek_katgoria_kapcsolo ON termek_kategoria
WHERE termek_kategoria_kapcsolo.kat_kapcs_kategoria_id = termek_kategoria.kat_id
AND termek.termek_id IN (SELECT kat_kapcs_termek_id FROM
termek_kategoria_kapcsolo WHERE kat_kapcs_kategoria_id = '$termek_kategoria')
";
This result:
Whats going wrong here?
What I want is when I select a categoria, the program give me the products, that are in the selected categoria.
I solved the problem:
$sql =
"
SELECT
t.termek_id,
t.termek_nev,
t.termek_cikkszam,
t.termek_status,
kapcs.kat_kapcs_kategoria_id,
kapcs.kat_kapcs_termek_id
FROM termek t
LEFT JOIN termek_katgoria_kapcsolo kapcs ON kapcs.kat_kapcs_kategoria_id = '$termek_kategoria'
WHERE t.termek_id = kapcs.kat_kapcs_termek_id AND t.$kereses_helye LIKE '%$kw%' ORDER BY t.$kereses_rendezes $kereses_sorrend
";

For each SQL result, another SQL query? in PHP

I need help at getting data from MySQL Database. Right now I have a query that gives me:
Tournament ID
Tournament Name
Tournament Entry fee
Tournament Start and End date
For tournaments I am registered in. Now I want, for each tournament I am registered in, to count how many users are in that tournament, my points in that tournament, etc.
That info is in table called 'ladder'
ladder.id
ladder.points
ladder.userFK
ladder.tournamentFK
Database: http://prntscr.com/99fju1
PHP CODE for displaying tournaments I am registered in:
<?php
include('config.php');
$sql = "SELECT distinct tournaments.idtournament, tournaments.name, tournaments.entryfee, tournaments.start, tournaments.end
from tournaments join ladder
on tournaments.idtournament= ladder.tournamentFK and ladder.userFK=".$_SESSION['userid']."
group by tournaments.idtournament";
$result = $conn->query($sql);
if($result->num_rows > 0){
while($row = $result->fetch_assoc()) {
$tournament="<li class='registered' data-id=".$row['idtournament']." data-entryfee=".$row['entryfee']." data-prize=".$tournamentPrize."><span class='name'>".$row['name']."</span><span class='entry-fee'>Entry fee: ".$row['entryfee']."€</span><span class='prize-pool'>Prize pool: €</span><span class='date-end'>".$row['start']."-".$row['end']."</span><span class='btns'><button>Standings</button></span></li>";
echo $tournament;
}
}
$conn->close();
?>
Usually you can combine JOIN, COUNT() and GROUP BY in your query.
Some examples:
MySQL joins and COUNT(*) from another table
This would be the query I think.Change column and table name if its not correct. Not tested but I am sure this will give you some idea to make required query
select count(ladder.tournamentId)as userCount,tournaments.name
from
ladder left join tournaments
on ladder.tournamentId = tournaments.id
where ladder.tournamentId in
(
select tournaments.id from
tournaments left join ladder
on ladder.tournamentId = tournaments.id
where ladder.userId='yourId'
) and ladder.userId <> 'yourId'
group by ladder.tournamentId

Not understanding the Join Function

Thanks in advance for any time you spend on my question.
I am trying to display data in a way that will display the manufacturer as a name instead of a number.
Basically when they store the data they choose a manufacturer from a drop down which is generated from a table.. IE Trogues = 1 so products stores the #1 so I know that any beer is associated with trogues is 1. Now I want to display the data but instead of having a 1 I would like to have Trogues be displayed. Where you see manufacturer in the echo code below..
I am not understanding the process logic here..
error_reporting(E_ALL);
ini_set('display_errors', 1);
$sql = "SELECT * FROM products
LEFT JOIN manufacturer
ON product.manufacturer = manufacturer.id
ORDER BY manufacturer.id, product.id";
$query = mysql_query($sql);
while($row = mysql_fetch_array($query)) {
echo "
<div class=reportclientproduct>".$row['manufacturer']." - <a href=".$row['website']." target=_blank>".$row['product']."</a></div>";
}
Have you tried the query like this:
$sql = "SELECT man.id AS manufac, products.product AS prod FROM products
LEFT JOIN manufacturer as man
ON product.manufacturer = manufacturer.id
ORDER BY manufacturer.id, product.id";
$query = mysql_query($sql);
while($row = mysql_fetch_array($query)) {
echo "
".$row['manufac']." - ".$row['prod']."
";
}
Assuming that the table products had a column named manufacturer which holds the ID of the manufacturer, and that both tables have columns name ID which hold the ID of the table item.
Also the JOIN functions may vary based on the database you use. But the aforementioned method is for mysql.

mysql return the total of rows for each user_id

$sql = "SELECT * FROM books LEFT JOIN users
ON books.readby=users.user_id WHERE users.email IS NOT NULL";
$result = mysql_query($sql);
while($row = mysql_fetch_array($result))
{
echo $row['readby']. " - read 10 books";
} //while ends
this is the code I have so far. I am trying to retrieve the number of books read by each user
and echo the results. echo the user_id and number of books he/she read
books table is like this : id - name - pages - readby
the row readby contains the user id.any ideas/suggestions? I was thinking about using count() but Im not sure how to go about doing that.
A subquery can return the count of books read per user. That is left-joined back against the main table to retrieve the other columns about each user.
Edit The GROUP BY had been omitted...
SELECT
users.*,
usersread.numread
FROM
users
/* join all user details against count of books read */
LEFT JOIN (
/* Retrieve user_id (via readby) and count from the books table */
SELECT
readby,
COUNT(*) AS numread
FROM books
GROUP BY readby
) usersread ON users.user_id = usersread.readby
In your PHP then, you can retrieve $row['numread'] after fetching the result.
// Assuming you already executed the query above and checked errors...
while($row = mysql_fetch_array($result))
{
// don't know the contents of your users table, but assuming there's a
// users.name column I used 'name' here...
echo "{$row['name']} read {$row['numread']} books.";
}
You can use count() this way:
<?php
$count = mysql_fetch_array(mysql_query("SELECT COUNT(`user_id`) FROM books LEFT JOIN users ON books.readby=users.user_id WHERE users.email IS NOT NULL GROUP BY `user_id`"));
$count = $count[0];
?>
Hope this helps! :)

Categories