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
Related
I have two different tables, one named users, and another named transactions. Transactions contains wallet1, wallet2, amount. Users contains user details such as firstname, lastname, and wallet. I am trying to display the corresponding first name and last name, depending on whether or not the SESSION_wallet is equal to wallet1 or wallet2 within transactions. I tried searching for a while, and came up with a solution for showing the correct display name for the first and last name making the transfer, however, I am trying to make it display the correct value for "Transfer to:"
Here is some of my code to get a better understanding of what I mean:
MySQLi Query:
$result2 = mysqli_query($link, "SELECT * FROM transactions INNER JOIN users ON transactions.wallet1 = users.wallet WHERE transactions.wallet1 = '" . $_SESSION["wallet"] . "' OR transactions.wallet2 = '" . $_SESSION["wallet"] . "' Order by transactions.id DESC LIMIT 5 ");
PHP Code:
<?php
if(mysqli_num_rows($result2) > 0)
{
while($row = mysqli_fetch_array($result2))
{
?>
The table that needs to display the transfer from, and transfer to:
<?php
if ($_SESSION["wallet"] == $row["wallet1"]) {
echo "<td>Transfer to ".$row["firstname"]." ".$row["lastname"]."</td>";
}
else if ($_SESSION["wallet"] == $row["wallet2"]) {
echo "<td>Transfer from ".$row["firstname"]." ".$row["lastname"]."</td>";
}
?>
Right now my tables are only showing the first and last name of the user that made the Transfer, however, I need it to display the first and last name of the user that the transaction is made to as well. The else if code is working correct, but the first part is not showing the corresponding value.
You will need to JOIN your transactions table to your users table twice, once to get each users name. Then to avoid duplicate column names overwriting the results in the output array, you will need to use column aliases. Something like this should work:
$result2 = mysqli_query($link, "SELECT t.*,
u1.firstname AS w1_firstname,
u1.lastname AS w1_lastname,
u2.firstname AS w2_firstname,
u2.lastname AS w2_lastname
FROM transactions t
INNER JOIN users u1 ON t.wallet1 = u1.wallet
INNER JOIN users u2 ON t.wallet2 = u2.wallet
WHERE t.wallet1 = '{$_SESSION["wallet"]}'
OR t.wallet2 = '{$_SESSION["wallet"]}'
ORDER BY t.id DESC
LIMIT 5 ");
Then you can access each user's names as $row['w1_firstname'] etc.:
if ($_SESSION["wallet"] == $row["wallet1"]) {
echo "<td>Transfer to ".$row["w2_firstname"]." ".$row["w2_lastname"]."</td>";
}
else if ($_SESSION["wallet"] == $row["wallet2"]) {
echo "<td>Transfer from ".$row["w1_firstname"]." ".$row["w1_lastname"]."</td>";
}
Note that ideally you should use a prepared query for this, for example:
$stmt = $link->prepare("SELECT t.*,
u1.firstname AS w1_firstname,
u1.lastname AS w1_lastname,
u2.firstname AS w2_firstname,
u2.lastname AS w2_lastname
FROM transactions t
INNER JOIN users u1 ON t.wallet1 = u1.wallet
INNER JOIN users u2 ON t.wallet2 = u2.wallet
WHERE t.wallet1 = ?
OR t.wallet2 = ?
ORDER BY t.id DESC
LIMIT 5");
$stmt->bind_param('ss', $_SESSION["wallet"], $_SESSION["wallet"]);
$stmt->execute();
$result2 = $stmt->get_result();
I'm practicing on a php website with reservations. I've made three tabs on which I want to display reservations for today and for the coming week.
So far I have this mysql query:
$sql = "SELECT *
FROM users
LEFT JOIN reserveringen ON (users.userID = reserveringen.userID)
WHERE reserveringen.kamertype = 1
AND reserveringen.datum <= DATEADD(day,+7, GETDATE())";
but I it doesnt display any results
Edit:
I have made an if-else statement saying if there are results display them else echo a message saying "there are no reservations for the coming week". This is the query for showing all reservations and it runs just fine:
$sql = "SELECT *
FROM users
LEFT JOIN reserveringen ON (users.userID = reserveringen.userID)
WHERE reserveringen.kamertype = 1`
The function name DATEADD() is a TransactSQL function. In MYSQL it is called DATE_ADD() and the parameters are different as well
So this is more likely to work
$sql = "SELECT *
FROM users
LEFT JOIN reserveringen ON (users.userID = reserveringen.userID)
WHERE reserveringen.kamertype = 1
AND reserveringen.datum <= DATE_ADD(CURRDATE(), INTERVAL 7 DAY)";
I have a page that is dynamically generated using PHP and a MySQL database. The page displays information about an event, and lists the dates that event will run.
My database has the following relevant tables:
events - containing the event name, cost etc
venue - containing venue information
instance - containing the event_id, venue_id, the date the event at that venue will run, and the capacity for that instance.
registration - containing the instance_id, and attendee_id.
To grab all the information to actually display the event information, I use the following code:
$eid = $_GET['event_id'];
$q = "SELECT e.event_name, e.event_description, e.event_byline, e.event_benefit, e.event_cost, e.event_exam, e.event_resi, i.venue_id, i.instance_id, i.instance_cap, v.venue_name, DATE_FORMAT( i.instance_date, '%M %D, %Y' ) AS DATE
FROM events AS e
INNER JOIN instance AS i ON e.event_id = i.event_id
INNER JOIN venue AS v ON i.venue_id = v.venue_id
WHERE e.event_id = $eid
ORDER BY i.venue_id, i.instance_date";
$cur_venue = 0;
$r = #mysqli_query ($dbc,$q) or die(mysqli_error($dbc));
$row = mysqli_fetch_array($r, MYSQLI_ASSOC);
Now, what I want to do is display a list, sorted by venue, of the instances for the relevant event, which I have done up to a point. However, what I also want to do is only display the instance if there is space left on that particular instance.
Since I know the capacity of each instance (from my instance_cap column), and I can COUNT the number of attendees registered to each instance, I figure I can do this thuswise:
do
{
$list_instance = $row['instance_id'];
$qRegs = "SELECT COUNT(delegate_id) AS regs FROM registration
WHERE registration.instance_id = $list_instance";
$rRegs = mysqli_query($dbc,$qRegs);
$registrations = mysqli_fetch_object($rRegs);
$capacity = $row['instance_cap'];
$availability = $capacity - $registrations->regs;
if ($availability > 0){ //if event has places available...
if ($cur_venue != $row['venue_id']) //and if the current venue is not the same as the venue id
{
echo '<li id="'.$row['venue_name'].'">'
$cur_venue = $row['venue_id'];
echo '<h4>'.$row['venue_name'].'</h4>';//display the venue name
}
echo ''.$row['DATE'].'' //display the date for current instance
echo '</li>';//close list tag
}
} while ($row = mysqli_fetch_array($r, MYSQLI_ASSOC));';
The problem I have is that this misses out the first instance and skips straight to the second one. I understand that this is probably due to the fact that I have called mysqli_fetch_array twice, so how I can work it so that this doesn't happen?
You should be able to run one query, and then just use the resultset. Try this:
SELECT e.event_name, e.event_description, e.event_byline,
e.event_benefit, e.event_cost, e.event_exam, e.event_resi,
i.venue_id, i.instance_id, i.instance_cap, v.venue_name,
DATE_FORMAT( i.instance_date, '%M %D, %Y' ) AS DATE
FROM events AS e
INNER JOIN instance AS i ON e.event_id = i.event_id
INNER JOIN venue AS v ON i.venue_id = v.venue_id
WHERE e.event_id = $eid AND i.instance_cap > (SELECT COUNT(r.delegate_id) FROM registration AS r WHERE r.instance_id = i.instance_id)
ORDER BY i.venue_id, i.instance_date
Granted, this is untested, so it might not work as-is.
EDIT: a sub-query is probably more correct. See the edited query above.
Put
mysqli_data_seek ( $r , 0 );
before the second mysqli_fetch_array to reset the internal pointer to the first instance.
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
Sorry let me revise. I have a three tables:
events_year
• EventID
• YearID
• id
Date
• YearID
• Year
Event
• EventID
• EventName
• EventType
i want to dispay a record from the three tables like so:
EventName - Year: Marathon - 2008
i linked it to a table called "members" which contains a ID number field (members-id)
so i can limit the results to members id = $un(which is a username from a session)
I need to join the three tables and limit the results to the specific ID number record
Here is my portion of the code:
$query = "SELECT * FROM members JOIN events_year ON members.id = events_year.id ";
"SELECT * FROM Event JOIN events_year ON Event.EventID = events_year.EventID WHERE username = '$un'";
"SELECT * FROM Date JOIN events_year ON Date.YearID = events_year.YearID WHERE username = '$un'";
$results = mysql_query($query)
or die(mysql_error());
while ($row = mysql_fetch_array($results)) {
echo $row['Year'];
echo " - ";
echo $row['Event'];
echo "<br>";
}
the notices are almost self-explaining. There are no 'Year' and 'EventName' fields in the resultset. It's difficult (or: impossible) to tell why this happens as you haven't given your table-structure, but i guess this: 'Year' is a field of the date-table, 'EventName' is a field of the event-table - you're only selecting from members so this fields don't occur.
I don't understand why there are three sql-statements but only one is assigned to a variable - the other two are just standing there and do nothing. Please explain this and put more information into your question about what you're trying to achive, what your table-structure looks like and whats your expected result.
I think what you really wanted to do is some kind of joined query, so please take a look at the documentation to see how this works.
finally, i think your query should look like this:
SELECT
*
FROM
members
INNER JOIN
events_year ON members.id = events_year.id
INNER JOIN
Event ON Event.EventID = events_year.EventID
INNER JOIN
´Date´ ON ´Date´.YearID = events_year.YearID
WHERE
members.username = '$un'
Does the field 'Year' exist in the query output ? I suspect not.
the string $query is only using the first line of text:
"SELECT * FROM members JOIN events_year ON members.id = events_year.id ";
and not the others.
The query itself is not returning any fields that are called Year or EventName.
Do a var_dump($row) to find out what is being returned.