How to make an effective sql query? - php

Following are the tables:
Table User:
User_Id = 1,2,3;
User_Name: A,B,C;
Table Business:
Business_Id = 1,2,3;
Business_Name: A,B,C;
Business_Detail: Details_A, Details_b, Details_c;
Table Visits:
Visit_Id = 1,2,3,4,5,6:
User_Id = 1,1,1,2,1,1;
Business_Id = 1,1,1,2,2,3;
I need to create a function that return a list of the visits and the information about the business that the user visited. So far I have got the list of the store the user has visited but don't know where to go from there.
function visit_count($user_id=1){
global $database;
$sql = "SELECT * FROM visits WHERE user_id ='{$user_id}' LIMIT 0 , 30";
$result_set = $database->query($sql);
$visits = mysql_fetch_array($result_set);
//Get the unique ids of the business
//Run another query that has the business information
//combing both queries.
}
Thanks for the quick response guys. It's pretty much what I am looking for I think I am looking for the query to return an object as following:
Object:
- Business:
- Business_id;
- Business_name;
- Visit_counts;
- Business:
- Business_id;
- Business_name;
- Visit_counts;
So basically the object will have the business information and the no of times that the user has visited the store.
Thanks much for all the help

Well, first off you should look into prepared statements, it is the current best practice for working with sql in PHP.
What it sounds like you need are joins.
$sql = "SELECT * FROM visits v
JOIN business b ON b.Business_Id = v.Business_Id
JOIN user u ON u.Business_Id = v.Business_Id
WHERE v.user_id ='{$user_id}' LIMIT 0 , 30";

SELECT Visits.* , Business.Business_Name, Business.Business_Details
FROM Visits
LEFT JOIN Business on Business.Business_Id = Visits.Business_Id
WHERE Visits.User_Id =1
try this SQL for each user

Try following SQL code:
SELECT business.business_id, business.business_name, COUNT(business.business_id) AS visit_counts
FROM business
LEFT JOIN visits
ON business.business_id = visits.business_id
GROUP BY business_id, user_id
Result:
business_id |business_name |visit_counts
1 A 3
2 B 1
2 B 1
3 C 1

You need Joins:
SELECT v.*, b.Business_Name, b.Business_Detail FROM visits as v
JOIN Business as b on b.Business_Id = v.Business_Id
WHERE v.user_id ='{$user_id}' LIMIT 0 , 30
Also - use mysqli and ensure you are sanitizing your inputs!
Edit
Follow #KHMKShore's advice on using prepared statements.

Related

Get all the members below me in an mlm module in PHP and MySQL

I have a database, as shown in this, any user can join with any sponsor ID, and they will get their own user ID which can lead the tree further. I want to get details of a particular user_id, say, '2'. I am expecting the output in which the user_id will be (3,4 since 3 is directly linked with 2 and 4 is linked directly with 3 which is linked with 2). Similarly if I select user_id 1, then I would get the resultant user_id (2,3,4,5, where 2 and 5 are directly linked to user_id 1 and 3,4 are indirectly linked to 1).
I have tried almost every possible while loop format, but I just can't get the output. Here is the final bit of my code, because I have deleted most of it:
<?php
include 'config.php';
$current_user='1';
$all = mysqli_query($con,"SELECT * FROM users");
while($all_array = mysqli_fetch_array($all)){
$all_sponsors = $all_array['sponsor_id'];
}
$below_details = mysqli_query($con,"SELECT * FROM users WHERE sponsor_id ='$current_user'");
while ($below_array = mysqli_fetch_array($below_details)){
$below_users = $below_array['user_id'];
}
?>
Any kind of help is appreciated. Feel free to ask me the details if there is any confusion in the question.
You can use a recursive CTE to retrieve all the members below a given id -
WITH RECURSIVE pyramid AS (
SELECT u.* FROM users u WHERE sponsor_id = 1 /* starting sponsor_id */
UNION ALL
SELECT u.* FROM pyramid p JOIN users u ON p.id = u.sponsor_id
)
SELECT * FROM pyramid;

How to properly write query SELECT'ing multiple tables

please advise on query below. I want to select multiple tables. entryId is from table stockTracking. I bet i should use JOIN or smt.. Cheers!
$updateEntryId = $_GET["entryId"];
$query = "SELECT *
FROM stockTracking, loggers, boxes
WHERE entryId ='$updateEntryId'";
$result = mysqli_query($connection, $query);
table
boxes|boxId boxQuantity boxName
2 10 CL64
loggers | loggerId loggerQuantity loggerName
2 10 34242342
stockTracking| entryId time destination reference
2 timestamp Paris 1312
I have updated query to following, however what wrong with my WHERE statement?
As i add WHERE entryId='$updateEntryId' if fails to display any results
$updateEntryId = $_GET["entryId"];
$query = "SELECT *
FROM stockTracking
JOIN loggers
ON entryId=loggerId
JOIN boxes
ON boxId=entryId
WHERE entryId='$updateEntryId'";
Yes, you are right. You should perform a JOIN operation among-st the tables like below. replace some_column in below sample sql code with your actual column name on which you have relationship between the tables
SELECT s.*
FROM stockTracking s
JOIN loggers l ON s.some_column = l.some_column
JOIN boxes b ON b.some_column = s.some_column
WHERE s.entryId ='$updateEntryId'
Try this out:
$updateEntryId = $_GET["entryId"];
$query = "SELECT *
FROM stockTracking s
JOIN loggers l
ON s.entryId=l.loggerId
JOIN boxes b
ON b.boxId=s.entryId
WHERE s.entryId='".$updateEntryId."'";
Join the tables as stated by #rahul but should be done in proper manner .. cheers!
SOLVED.
Problem was in $updateEntryId=$_GET["entryId"];
It had no results, since as search bar was showing http://stock/edit.php?id=2, it was looking for $_GET["id"] and not $_GET["entryId"].

Picking which data to view in group by

So yesterday, I am trying to sort data in groups made by Group by
I must select which data I want to show in those group
There is list of debts and each person may be in debt in the past but never have more than 1 unpaid debt
I need to know how many times how many times each user have been in debt before this last debt.
This is the column in the data base
Table "Users"
uid | name | date_of_birth
Table "Debt"
uid | debt_duration | paid_count | created_date
I end up with a hack like this in php
$res = mysql_query( "
SELECT * FROM Debt
JOIN Users
WHERE Users.uid = Debt.uid
ORDER BY created_date
GROUP BY Debt.uid");
while( $row = mysql_fetch_array( $res ) ){
$uid = $row['uid'];
$r = mysql_fetch_array( mysql_query("SELECT COUNT(*) FROM Debt WHERE uid = $uid") );
$previous_debts_count = $r[0];
}
This script is quite heavy but fortunately my client doesn't complain.
The script run at around 3 seconds top
But I need to know better ways to do this
sorry for the strange formatting, I am new here ...
I think the query you want is this:
SELECT Users.uid, COUNT(*) as cnt
FROM Debt JOIN
Users
ON Users.uid = Debt.uid
GROUP BY Debt.uid
ORDER BY created_date ;
Just loop through the results and don't use multiple queries for this. Check that Users.uid is the primary key on the users table. And add an index on debt(uid) to improve performance.
First of all, you should never use * in an SQL statement.
It makes the query highly vulnerable to SQL injection.
And I recommend you to use a PDO or a PHP framework.
Try this:
SELECT COUNT(Debt.uid) AS users
FROM Debt
LEFT JOIN Users
ON Users.uid = Debt.uid
GROUP BY Debt.uid

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 :)

Mysql selection from more than one table

SELECT * FROM dog WHERE (SELECT calluser FROM jos_users WHERE `user_id`='".$cid."')=Subcode
$cid is the identifier in jos_users, which tells us which users we're fetching data about
The data I want to fetch is within "dog", and calluser is the identifier between the two (which tells us who's dogs are who's)
I need to be able to call only the dogs relevant to the user in question, but it also has to be performed in one query. Can anyone help? Much appreciated.
You need to use joins.
Read this tutorial: http://www.tizag.com/mysqlTutorial/
Your query should look something like this:
$cid = mysql_real_escape_string($_GET['cid']);
$query = "SELECT d.* FROM dog d
INNER JOIN jos_users ju ON (d.user_id = ju.id)
WHERE ju.id = '$cid' ";
If I got you right (and the id column in the dog-table links to the calluser column in the jos_user-table) the query should be
SELECT d.* FROM dog AS d JOIN jos_user AS u ON d.id = u.calluser WHERE u.user_id = '$cid'
If not please explain your data structure in more detail (maybee small ER diagram).

Categories