PHP / MySQL - Constructing a Query - php

Im trying to put together a SQL query and its got me all confused, i have written out in normal language what i need, i cant seem to get it.
select * from introles where introle = $key
then check the table 'availability' for the user_id taken from the introles table
then out of those results, check that $_POST['date'] is not equal to the date in the 'availability' table
Any help would be amazing :)
EDIT: The table structure is as follows
Table introles has the following
id
user_id
introle
Table availability has the following
id
user_id
date

can you try
'$variable'
instead of
$variable
for all variables in sql query?

$query = "SELECT a.id AS aId, i.id AS iId, a.user_id, introle, date FROM availability AS a, introle AS i WHERE date != {$_POST['date']} AND a.user_id IN (SELECT user_id FROM introle WHERE introle = {$key})";

Related

Multiple PHP subqueries not giving desired result

I have a MySQL table from which I want to extract attendance information(Student Id, course/subject for attendance, date range,whether the student was present or not). I have written the following query:
SELECT
COUNT(a_id),
(
SELECT COUNT(*) FROM attendance
WHERE state = 'present'
AND `dater` BETWEEN '$a' AND '$b'
) AS Count,
stud_id
FROM attendance
WHERE
stud_id =(SELECT id FROM users WHERE NAME = '$stud')
Which is giving me the correct results, but when I change the student,its not giving me the correct count for the days recorded for present. Not mention that I have not yet added the course parameter into the query
The MySQL table is as follows:
I need help for the query to return the desired results(Count the accurate days present for each student, as well as adding the course parameter into the query so that the query will look for attendance records for a specific course, for a specific student, for a specified date range).
Looks like you want to seperate your queries:
Select (select count(*) from <database>.attendance where state = 'present' AND (dater between '$a' and '$b') AND name=(SELECT id FROM users WHERE NAME = '$stud')) as present, (select count(*) from <database>.attendance where state = 'absent' AND (dater between '$a' and '$b') AND name=(SELECT id FROM users WHERE NAME = '$stud')) as absent from <database>.attendance WHERE stud_id =(SELECT id FROM users WHERE NAME = '$stud');
try this :)
Resolved it using JOIN as follows:
SELECT u.id, a.stud_id, a.course_id, count(*) FROM attendance a
JOIN users u ON u.id=a.stud_id
JOIN courses c ON c.c_id=a.course_id
WHERE a.state='present' and dater between '2017-09-01' and '2017-09-14'
GROUP BY a.stud_id, a.course_id;
Thanks for your help.

Need help writing an SQL query for a select statement

I need help with an SQL query.
I want to show lines from my test_related_orders table where the current user id equals the user_id in my test_related_orders table and where order_unlock_time (from my table) is <= acutal timestamp. Until here all works fine. But now it gets complicated.
I also need to check/restrict in my wp_posts table if there is an post_author equals to my test_related_orders user_id who has an existing order_number same as from my test_related_orders order_number.
If this statement is true the associated lines from my test_related_orders will be shown. If this statement is false there should be no associated lines.
(So when I delete an order in the woocommerce frontend the statement should'nt return a string for this entry.)
Here is my existing code:
$user_id = get_current_user_id();
//Timestamp for current system time
date_default_timezone_set("Europe/Berlin");
$timestamp = date("Y-m-d H:i:s");
//Database Query
$abfrage = "SELECT * FROM test_related_orders WHERE user_id = '$user_id' AND order_unlock_time <= '$timestamp'";
I think I can use an INNER JOIN and I've tried it here:
INNER JOIN wp_posts ON '$user_id' = post_author WHERE....
but it's to complicated for me as a beginner.
Here are my database structures:
The test_related_orders structure:
The order_number looks like: DE-1016-835 and the user_id as a normal number/id like 1 in this example.
The wp_posts database structure:
The last picture is an example entry from the wp_posts. The problem is that I have to grab the order number from post_title and for this I have to remove the first word "Lieferschein" from this title to get the order_number and there's no extra field for the number...
Thank you for your help! I hope I explained it completely.
First problem to solve is getting the order number from the post_title so that you can compare the values in your inner join. A primitive way of doing this, assuming the order number is always in form AA-DDDD-DDD would be
SELECT right(post_title, 11) as posts_order_number
As you've already discovered, an inner join is what you need, as it'll only return results where the tables match. Note you usually join tables based on their columns, rather than directly comparing to your '$user_id' string (and you've already filtered for this in your where clause).
You can join on more than one field at a time, to match on order number as well as user_id.
Your query now becomes:
SELECT *
FROM test_related_orders tro
INNER JOIN wp_posts p
ON tro.user_id = p.post_author
AND tro.order_number = right(p.post_title, 11)
WHERE tro.user_id = '$user_id' AND order_unlock_time <= '$timestamp'

How to update value when moving row to another table

I have 2 tables:
Table1
Table2
When I move a row from table1 to table2, I also want to update the datetime field and 1 more field.
Say both table have identical column like this:
id
shipped_by
datetime
other_column
I have the following sql line, but it is not working of course. But I want to have it something like that.
$query = "INSERT INTO table2
SELECT * FROM table1
WHERE id = '$id' UPDATE table2
SET shipped_by='$shipped_by', datetime='$datetime'";
The variable $shipped_by selects the userid, and $datetime date from now.
Can anyone help me with this sql code to make it work? I cannot figure it out.
Thank you.
To insert data form table1 with some column data modified can be done with insert and select without update.. select * should be used here, each column must be listed except for modified ones..
$query = "INSERT INTO table2
SELECT id, '$shipped_by', '$datetime', other_column FROM table1
WHERE id = '$id'";

MySql - if there is no record, insert multiple rows

Before asking this question, I already search a lot of entries on Google and StockOverflow. Nothing can fulfil my question.
There are two tables - group_sale_bonuses and members. I want to check is already there records with product_id "1" in the group_sale_bonuses.
If not, I want to insert all records from members table into group_sale_bonuses with product_id "1".
My overall requirement is as follow:
IF ((Select count(id) from group_sale_bonuses where product_id = 1) = 0) THEN
INSERT INTO group_sale_bonuses (member_id, product_id, quantity_counter, credit)
SELECT id, 1, 0, 0 FROM members
END IF
But this sql causes the errors.
I know there are solutions about Insert Ignore, Where Not Exists.
But these conditions checking are based on per each record. I have thousands of records in members table. I want to make condition checking just one time like in my above sql example.
By the way, I will use this Sql in Php web application.
You could just set the code in a WHERE clause instead of the IF.
INSERT INTO group_sale_bonuses(
member_id,
product_id,
quantity_counter,
credit)
SELECT
id, 1, 0, 0 FROM members
WHERE(
SELECT
count(id) FROM group_sale_bonuses
WHERE product_id = 1
) = 0;
This should do it for all product_id's
SELECT m.product_id, m.member_id FROM members AS m
LEFT JOIN group_sale_bonuses AS gsb ON gsb.product_id = m.product_id
WHERE gsb.product_id IS NULL ;
You can filter it to a specific product_id by adding to the where clause
SELECT m.product_id, m.member_id FROM members AS m
LEFT JOIN group_sale_bonuses AS gsb ON gsb.product_id = m.product_id
WHERE gsb.product_id IS NULL AND m.product_id = 1;
Take a look at this SQLfiddle: http://sqlfiddle.com/#!2/8482c/2

How do I form an SQL query using DATE_SUB to retrieve and post yesterday's data?

Here's my query:
$sql = $db->Query("SELECT a.uid, SUM(a.today_clicks) AS clicks, b.login FROM user_clicks a LEFT JOIN users b ON b.id = a.uid WHERE b.login != '' GROUP BY a.uid ORDER BY clicks DESC LIMIT 3");
Here's the code i'm using for getting the top 3 users for today:
<tr><?
$tops = $db->FetchArrayAll($sql);
foreach($tops as $top){
echo '<td>'.$top['login'].'</td>';
}
?></tr>
Which gives me the top 3 user names with the most clicks for today.
Here's my table structure:
Table name :"user_clicks"
6 fields
uid
module
total_clicks
today_clicks
max_clicks
daily_clicks
How can i get the same data but just from a day before?
Thanks in advance!
Here is one generic way to filter the columns with a date corresponding to yesterday:
SELECT
*
FROM
mytable a
WHERE
DATE_FORMAT(DATE_SUB(NOW(), INTERVAL 1 DAY), "Y-m-d") = DATE_FORMAT(a.date, "Y-m-d")
There is not enough information about your table structure to say how you would apply it in you case. So you will have to figure it out :)

Categories