Does't selecting the good value in sql - php

Hello I have a sql syntax and it always take the last record and doest check the other condition.
SELECT *
from projetstaches ,users,timesheets
WHERE `prtTimeSheetId` = ( SELECT MAX( `prtTimeSheetId` ) FROM projetstaches ) AND usrId = 16 AND timId = prtTimeSheetId
I'm working with php and sql but I know this is my syntax is not good.
It's always give me my last record . It's do not take the last record of my user 16 . Cause my last record its for my user 7 . Have any idea why?
So I need to take the last projettime sheet of my user 16
**EDIT **
here what look like my data http://pastebin.com/6LBwGtc3

I suppose your query should look like this:
SELECT *
from
projetstaches
inner join
timesheets
on (timesheets.timId = projetstaches.prtTimeSheetId)
inner join
users
on (users.usrId = timesheets.timUserId)
WHERE
users.usrId = 16
order by timesheets.timId desc
limit 1
To understand how it works I suggest you to play with this query:
remove where - check result
remove limit - check result

Related

Combine multiple queries to get single sum answer

Quite new to all the SQL/PHP stuff - dabbled with basic queries and outputting them to PHP previously but now trying something a bit more complicated and hoping someone can help with this as I've been trying to work it out with no luck so far:
I have 2 MS SQL tables:
Table 1 - Faults
faultid ... requestnumber
1 ........... 6
2 ........... 5
3 ........... 6
Table 2 - actions
faultid ....who ..... when...... timetaken
1.......... John....... Mon......... 1.00
2.......... Peter...... Mon.......... 2.00
3.......... Luke....... Tues........ 1.00
2.......... John....... Tues........ 0.5
1.......... Mike....... Mon......... 0.75
What I am trying to achieve is create a variable I can use in a front end php based webpage that gets a sum of the timetaken column in Table 2 where the requestnumber in Table 1 is equal to a specific number (i.e. 6)
I'm guessing it will start with something like:
$sql1 = "select faultid FROM Faults WHERE requestnumber = '6'";
$sqlresult = sqlsrv_query($conn, $sql1);
while ($row = sqlsrv_fetch_array($sqlresult)){
}
After that I get a bit stuck. How do I take each result from this and then run another query to get the sum of the timetaken column in Table 2 for just the corresponding faultid's? I want to hazard a guess at using foreach but not sure on the syntax (or even if I'm guessing correctly).
So in this example I would get back a result of 2.75 as a variable in PHP.
Any help would be appreciated. Thanks in advance.
Andy
Best to use just one SQL-statement
$sql = 'SELECT SUM(t2.timetaken)';
$sql .= ' FROM Faults t1 INNER JOIN actions t2 ON (t2.faultid = t1.faultid)';
$sql .= ' WHERE t1.requestnumber = ?';
Use this as prepared statement and pass your requestnumber (6 or something) as argument when executing this statement.
To get all or multiple sums you can use group by (maybe combine with WHERE):
SELECT t1.requestnumber, SUM(t2.timetaken)
FROM Faults t1
INNER JOIN actions t2 ON (t2.faultid = t1.faultid)
GROUP BY t1.requestnumber
Edit:
According to your own comment, you can use a SELECT with subquery, but use IN, not =. When using '=' the subquery must return only one row.
select SUM (timetaken) FROM actions WHERE faultid IN (select Faultid from Faults WHERE requestnumber = '6')
-- ^^
But this way is usually slower than the one I posted above

Multiple Select Query MySQL without while loop

I have two different tables where I need to fetch the list of store ids from one table and then find the list of coupons for those store ids.
Currently,
SELECT `storename` FROM `stores` where `brandname` = 21
This will return something like
Store 1
Store 2
Store 3
Store 4
And I need to to run another query like
SELECT * FROM `coupons` where `storename` = {{All these stores}}
I can't use while loops because, the number of stores comes from first query can't be determined and the the output I want was not coming as expected while using while loop as I am trying to do something like
while(first query output get storename)
{
do query here
while(second query output get all coupons per store)
{
// All coupons display here.
}
}
This is making quite complicated as well, is there anyway that I can tweak my SQL query and get results easily?
Thanks
you can use this query:
SELECT * FROM `coupons`
where `storename` IN (
SELECT `storename` FROM `stores` where `brandname` = 21);
$query = 'SELECT t.storename, h.couponid AS couponsid, h.coupon AS couponvalue'
. ' FROM #__stores AS t'
. ' LEFT JOIN #__coupons AS h ON h.storename = t.storename'
. ' where `brandname` = 21'
. ' ORDER BY anything you like'
;

How to count if value of a variable is repeated?

I am learning how to work with MySQL, and at the moment I succeed to show data from my table, using:
while($objResult2 = mysqli_fetch_assoc($objQuery_product)) {
Results are shown by using this variable $objResult2["id_product"]; this way i can take from DB any field I want like: $objResult2["name"]; $objResult2["email"]; etc.
But what i do if i have in the table more rows with the same id_product?
I want to write a if statment, which counts if id_product repeats. How to do that? If it is a lot of work, atleast please give me an idea of the right tutorial that I must read. Because i am trying second day to fix this, and searched google but i didnt find what i need, or maybe i coulndt understand it....
This is my query
$sql_product = "SELECT * FROM ps_product AS prod";
$join_product = " LEFT JOIN ps_product_lang AS lang ON lang.id_product = prod.id_product";
$join2_product = " LEFT JOIN ps_stock_available AS stok ON stok.id_product = prod.id_product";
$where_product =" WHERE prod.id_category_default = $idp AND lang.id_lang = 8";
$sql_product = $sql_product.$join_product.$join2_product.$where_product;
$objQuery_product = mysqli_query($objConnect, $sql_product) or die ("Error Query [".$sql_product."]");
You can simple remove the same id_product using DISTINCT keyword in your query. Such as:
SELECT DISTINCT id_product FROM my_table
This will give you results with different ids only.
The second way of doing it is taking the output values inside an array.
In your while loop:
$my_array[] = $objResult2["id_product"];
Then using array_filter remove all the duplicates inside the array.
YOu can also use array_count_values() if you want to count the duplicate values.
Ok here we go. For example you are fetching data with this query.
select id_product, name from PRODUCTS;
Suppose above query gives you 5 records.
id_product name
1 bat
2 hockey
2 hockey
3 shoes
4 gloves
Now you got 2,2 and hockey, hockey. Instead of thinking this way that you have to introduce an if statement to filter repeating records or same name or id_product records.
Rewrite your sql query like this.
select distinct id_product, name from PRODUCTS;
Or if you need count of each then my friend you will write your query something like this...
Graham Ritchie, if Andrei needs count of each repeating record then we will do something like this in our query.
SELECT PRODUCT_ID,
COUNT(PRODUCT_ID) AS Num_Of_Occurrences
FROM PRODUCTS
GROUP BY PRODUCT_ID
HAVING ( COUNT(PRODUCT_ID) > 1 );
SELECT id_product,COUNT(*) AS count
FROM tablename
GROUP BY id_product;
This query will then return you two items in your query
$objResult2["id_product"] //and
$objResult2["count"]
The if statement is then just
if($objResult2["count"] > 1){
//Do whatever you want to do with items with more than 1 occurence.
//for this example we will echo out all of the `product_id` that occur more than once.
echo $objResult2["id_product"] . " occurs more than once in the database<br/>";
}

how to set $_SESSION variable to use in sql query?

im not sure if i've got this right but i could do with some help to point me in the right direction please.
basically i have a table called ptb_stats. this table lay out looks like this:
user_id | user_postcode
1 m3 4
2 m3 4
3 kt1 3
4 sm2 7
i am trying to generate a mysql query that will bring up all the users that have matching postcodes.
so for instance if user 1 / user_id 1 is logged in then they will see user 2 who has the same postcode as them (begining with m3 4)
this tells the user aproximately that user 1 and user 2 are within 5 miles of each other as an example.
i've got a working query which is this:
function get_local_users() {
global $connection;
$query = "
SELECT *
From ptb_stats, ptb_users
WHERE ptb_stats.user_id=ptb_users.id
AND ptb_stats.user_postcode='m3 4'
AND ptb_users.id!=".$_SESSION['user_id']."";
$local_set = mysql_query($query, $connection);
confirm_query($local_set);
return $local_set;
}
at the moment im having to enter the postcode manually into the query for it to work. my problem is that i need to assign a session variable i believe which will tell the query to match users with the same postcodes to the user who is logged in.
at the moment i have $_SESSION['user_id'] set as a variable but someone previously set this variable and i am trying to fix all their work but am unable to get in touch with the guy who did it. So i don't understand session variables. i thought i could just change $_SESSION['user_id'] to $_SESSION['user_postcode'] and it would work, but basically what i need to do is some how get the query to say:
if the logged in user's user_postcode is (whatever value) and their are other users with matching user_postcodes then display these.
can someone please show me what i would need to do to get this to work. i would really appreciate it. thank you.
SELECT a.*
FROM
tableName a
INNER JOIN
(
SELECT user_postcode
FROM tableName
GROUP BY user_postcode
HAVING COUNT(*) > 1
) b ON a.user_postcode = b.user_postcode
SQLFiddle Demo
SQLFiddle Demo (with filter)
UPDATE 1
function get_local_users()
{
global $connection;
$query = " SELECT a.*
FROM ptb_stats a
INNER JOIN
(
SELECT user_postcode
FROM ptb_stats
GROUP BY user_postcode
HAVING COUNT(DISTINCT user_id ) > 1
) b ON a.user_postcode = b.user_postcode
WHERE a.user_id <> " . $_SESSION['user_id'];
$local_set = mysql_query($query, $connection);
confirm_query($local_set);
return $local_set;
}
As a sidenote, the query is vulnerable with SQL Injection if the value(s) of the variables came from the outside. Please take a look at the article below to learn how to prevent from it. By using PreparedStatements you can get rid of using single quotes around values.
How to prevent SQL injection in PHP?

PHP MySQL - selecting values from table 1 which are not in table 2

This may be simple to solve but I'm having trouble with this piece of code - I'm a self taught newbie with PHP, and the code I've come up with doesn't seem to want to work.
The pages are for an online entry system for a sports competition. Judges' details are stored in table "club_judges", and users can enter them into a competition by copying them into "competition_judges". This is done via a checkbox form in a table.
I want to add functionality whereby judges who are already added to the competition do not appear in the import form, however my code does not seem to work. I am using a unique field of "bg_number" (the sport's identification number) to search for an existing entry.
Current code:
$existing_judges = mysql_query("SELECT bg_number FROM competition_judges WHERE competition='Test Competition'");
$existing_judges_fetch = mysql_fetch_array($existing_judges);
$existing_judges_array = "('" . implode( "', '", $existing_judges_fetch ) . "');" ;
$query = "SELECT * FROM club_judges WHERE (`club`='Test Club') AND (`bg_number` NOT IN '$existing_judges_array') ORDER BY name ";
$result = mysql_query($query) or die(mysql_error());
Error displayed:
You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near ''('1234567', '1234567');') ORDER BY name' at line 1
For reference 1234567 is the bg_number for my test judge.
Any help would be greatly appreciated!
why dont u use just one query
SELECT *
FROM club_judges
WHERE `club`='Test Club'
AND `bg_number`
NOT IN (SELECT bg_number FROM competition_judges WHERE competition='Test Competition')
ORDER BY name
Use can use a single query instead like this:
$query = "SELECT * FROM `club_judges` WHERE `club`='Test Club'
AND
`bg_number` NOT IN
(SELECT `bg_number` FROM `competition_judges` WHERE `competition`='Test Competition')
ORDER BY `name` ";
$existing_judges_fetch = mysql_fetch_array($existing_judges);
$result = mysql_query($query) or die(mysql_error());
here's a JOIN version
SELECT a.*
FROM club_judges a
LEFT JOIN competition_judges b
ON a.bg_number = b.bg_number AND
b.competition='Test Competition'
WHERE b.bg_number IS NULL AND
a.club = 'Test Club'
ORDER BY a.name
To fully gain knowledge about joins, kindly visit the link below:
Visual Representation of SQL Joins

Categories