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?
Related
I have a table on my database which called topics(topic_id,topic_subject,topic_content,topic_date,topic_cat,topic_comm,topic_by,votes,tags,views,flags), from this table i want to echo
10 top users(topic_by) with the most topics(max number of topics) on a specific community(topic_comm). What PDO query should i use ? I think need something like below:
$sql = $conn -> prepare("SELECT topic_by WHERE topic_comm=:comm AND ( MAX COUNT(topic_id) )")
Let construct the query step by step. In order to get the top 10 user by most topic by community, you need to compute number of topic by each user on that community.
SELECT topic_by, COUNT(*) AS total_topic FROM topic
WHERE topic_comm = :comm GROUP BY topic_by
Then, you want to get the top 10 user, you can use basic subquery and LIMIT. So the final query
SELECT * FROM (
SELECT topic_by, COUNT(*) AS total_topic FROM topic
WHERE topic_comm = :comm GROUP BY topic_by
) AS t ORDER BY t.total_topic DESC LIMIT 10
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
I have an hard time to retrieve data in a table from MySQL database.
I have 2 different database that cannot be merge but there is a table in the first database that is identical to the second database.
Description Database 1 table: areas : ar_id, name, password.
Description Database 2 table: user : id, username, pass.
Now, When the user Login, He logs in the 2nd database. in each page of the user I have use $_SESSION['username'] to call the username.
Importantly, In every page, I have table that displays data from different tables using the username in the 2 Database; this else the SQL to be specific and only provide each user with their own information. and That's Ok. This is the SQL:
SELECT Client_table.Name, Client_table.Client_Id FROM Client_table, user WHERE user.username = '" . $_SESSION['username'] . "' AND Client_table.Branch = user.area Order by Name ASC
In one of the page, I totally using the 1st Database with this SQL to display data in the table :
select site_id, site_name from sites WHERE srep_id = 5
AND status = 1 or status = 2
order by site_name asc
QUESTION: I would like to display this SQL data in a table by using the username or id from the 2nd database BUT is returns Empty Table (I include both Database in this page). This is my current SQL but still not displaying anything:
SELECT cl.client_name, st.site_id, st.site_name
FROM Database1.sites st
JOIN Database2.user u ON u.id = st.ar_id
JOIN Database1.clients cl ON cl.client_id = st.client_id
WHERE Database1.st.name = '".$_SESSION['username']."'
AND st.status > 0
ORDER BY st.site_name ASC
NOTE: This is a major problem that took me almost a week!
Please some one help!
I think I have an answer.
After browsing and doing some search, I sound that I can make use of the $_SESSION here and Also, This was my final SQL Statement that Helped me to Connect the 2 Database from the same SQL Statement by using variable in PHP Script.
session_start();
$result = mysql_query("SELECT cl.client_name, st.site_id, st.site_name, ar.rep_id
FROM sites st
JOIN areas ar ON ar.rep_id = st.srep_id
JOIN clients cl ON cl.client_id = st.client_id
WHERE st.srep_id = '".$_SESSION['userarea']."'
AND st.status > 0
ORDER BY st.site_name ASC");
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
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/>";
}