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)";
Related
I am trying to get the Total Sum of values from a table. Query works without WHERE Clause, but i need to get the total sum per user. Like user ABC has 100USD and user BDC has 200USD. Here is the code
$PWithdrawls = mysqli_query($con, "SELECT * FROM withdraw WHERE status='Pending'");
$S_NO = 0;
while ($row = mysqli_fetch_assoc($PWithdrawls)) {
$S_NO++;
$posted_by = mysqli_query($con,"SELECT * FROM users WHERE userId=".$row['seller_id']);
$user_ad = mysqli_fetch_assoc($posted_by);
$TotalOrders_Amount = mysqli_query($con, "SELECT SUM(amount) as total FROM orders WHERE userId=".$row['seller_id']);
$sum_amount = mysqli_fetch_assoc($TotalOrders_Amount);
$sum = $sum_amount['total'];
And here is my call
<td>$<?php echo $sum; ?></td>
Here is DB
Think you have error in your SQL Query:
SELECT SUM(amount) as total FROM orders WHERE userId=".$row['seller_id'] GROUP BY userId LIMIT 1
You need to use GROUP BY to get actual SUM. Also you can get all users with Total, there is no need to second query:
SELECT u.*, SUM(o.amount) AS total
FROM users u
LEFT JOIN orders o ON (o.userId = u.id)
GROUP BY u.userId
This should get you entire user row + total of their orders.
I found the issue. I was calling the wrong variable. userId was not in my table, it was seller_id. So correct query was
$TotalOrders_Amount = mysqli_query($con, "SELECT SUM(amount) as total FROM orders WHERE seller_id=".$row['seller_id']);
Thanks to everyone. I really appreciate.
I am making a site where you can make posts and read post and now I am writing some code to filter these posts (like sort by 'new' or 'most liked')
I have this as query:
$search_query="SELECT Posts.user, Posts.title, Games.name,
Posts.text, Posts.time, Posts.attachement
FROM Posts
INNER JOIN Games ON Posts.game = Games.id
WHERE Posts.game = '$game'
AND tag = '$tag' AND subtag = '$subtag'"
or die("The search_query on the database has failed!");
The normal $search_query works fine.
Now I want to extend this query if the user wants to sort the posts, for example posts of last week, day etc.:
if(!empty($_POST['time']))
{
$search_query= "SELECT * FROM $search_query
WHERE time < DATE_SUB(now(), INTERVAL $time)";
}
But this query doesn't work, cause I get this error:
mysqli_num_rows() expects parameter 1 to be mysqli_result, bool given in
I have read that this means that there is error in the query.
Does anyone know how I can fix this?
All you need to do is simply add the additional clauses to the existing WHERE
if(!empty($_POST['time']))
{
$search_query .= " AND time < DATE_SUB(now(), INTERVAL $time)";
}
PS the or die() on here makes no sense as you are only putting text into a string variable, not executing it.
$search_query="SELECT Posts.user, Posts.title, Games.name,
Posts.text, Posts.time, Posts.attachement
FROM Posts
INNER JOIN Games ON Posts.game = Games.id
WHERE Posts.game = '$game'
AND tag = '$tag' AND subtag = '$subtag'"
or die("The search_query on the database has failed!");
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
I am trying to calculate how much a user has earned so it reflects on the users home page so they know how much their referrals have earned.
This is the code I have.
$get_ref_stats = $db->query("SELECT * FROM `members` WHERE `referral` = '".$user_info['username']."'");
$total_cash = 0;
while($ref_stats = $get_ref_stats->fetch_assoc()){
$get_ref_cash = $db->query("SELECT * FROM `completed` WHERE `user` = '".$ref_stats['username']."' UNION SELECT * FROM `completed_repeat` WHERE `user` = '".$ref_stats['username']."'");
$countr_cash = $get_ref_cash->fetch_assoc();
$total_cash += $countr_cash['cash'];
$countr_c_rate = $setting_info['ref_rate'] * 0.01;
$total_cash = $total_cash * $countr_c_rate;
}
It worked fine when I just had
$get_ref_cash = $db->query("SELECT * FROM `completed` WHERE `user` = '".$ref_stats['username']."'");
but as soon as I added in the UNION it no longer calculated correctly.
For example, there is 1 entry in completed and 1 entry in completed_repeat both of these entries have a cash entry of 0.75. The variable for $countr_c_rate is 0.10 so $total_cash should equal 0.15 but instead it displays as 0.075 with and without the UNION it acts as if it is not counting from the other table as well.
I hope this makes sense as I wasn't sure how to explain the issue, but I am very unsure what I have done wrong here.
In your second query instead of UNION you should use UNION ALL since UNION eliminates duplicates in the resultset. That is why you get 0.075 instead of 0.15.
Now, instead of hitting your database multiple times from client code you better calculate your cash total in one query.
It might be inaccurate without seeing your table structures and sample data but this query might look like this
SELECT SUM(cash) cash_total
FROM
(
SELECT c.cash
FROM completed c JOIN members m
ON c.user = m.username
WHERE m.referral = ?
UNION ALL
SELECT r.cash
FROM completed_repeat r JOIN members m
ON r.user = m.username
WHERE m.referral = ?
) q
Without prepared statements your php code then might look like
$sql = "SELECT SUM(cash) cash_total
FROM
(
SELECT c.cash
FROM completed c JOIN members m
ON c.user = m.username
WHERE m.referral = '$user_info['username']'
UNION ALL
SELECT r.cash
FROM completed_repeat r JOIN members m
ON r.user = m.username
WHERE m.referral = '$user_info['username']'
) q";
$result = $db->query($sql);
if(!$result) {
die($db->error()); // TODO: better error handling
}
if ($row = $result->fetch_assoc()) {
$total_cash = $row['cash_total'] * $setting_info['ref_rate'];
}
On a side note: make use of prepared statements in mysqli instead of building queries with concatenation. It's vulnerable for sql-injections.
With $countr_cash = $get_ref_cash->fetch_assoc(); you only fetch the first row of your result. However, if you use UNION, you get in your case two rows.
Therefore, you need to iterate over all rows in order to get all values.
Ok, So there is only one row in members table. You are iterating only once on the members table. Then you are trying to get rows using UNION clause which will result in two rows and not one. Then you are just getting the cash column of the first row and adding it to the $total_cash variable.
What you need to do is iterate over the results obtained by executing the UNION query and add the $total_cash variable. That would give you the required result.
$get_ref_stats = $db->query("SELECT * FROM `members` WHERE `referral` = '".$user_info['username']."'");
$total_cash = 0;
while($ref_stats = $get_ref_stats->fetch_assoc()){
$get_ref_cash = $db->query("SELECT * FROM `completed` WHERE `user` = '".$ref_stats['username']."' UNION SELECT * FROM `completed_repeat` WHERE `user` = '".$ref_stats['username']."'");
while($countr_cash = $get_ref_cash->fetch_assoc()){
$total_cash += $countr_cash['cash'];
}
$countr_c_rate = $setting_info['ref_rate'] * 0.01;
$total_cash = $total_cash * $countr_c_rate;
}
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.