I like to use self explaining names for associative selects, and sometimes it's even mandatory to avoid duplicates, so I use the AS keyword alot. But it's giving me some trouble with left joins.
This works:
$sql = "SELECT *,
projects.id as projects_id
FROM projects";
$sql .= " LEFT JOIN".
" (SELECT
projectfiles.id as projectfiles_id,
projectfiles.fileID as projectfiles_fileID,
projectfiles.projectID as projectfiles_projectID
FROM projectfiles
) AS projectfiles".
" ON projects.id = projectfiles_projectID";
However now I end up with useless data from projects, because it also picks up the fields userID and name, which I don't need. It's also picking up the id twice.
So I tried changing it to;
$sql = "SELECT
projects.id as projects_id
FROM projects";
With the ON line becoming
" ON projects_id = projectfiles_projectID";
But that gave the error Unknown column projects_id
So I tried
" ON projects.projects_id = projectfiles_projectID";
But still the same error
I then started experimenting, and tried (as a test)
$sql = "SELECT id,name,userID FROM projects";
$sql .= " LEFT JOIN".
" (SELECT
projectfiles.id as projectfiles_id,
projectfiles.fileID as projectfiles_fileID,
projectfiles.projectID as projectfiles_projectID
FROM projectfiles
) AS projectfiles".
" ON projects.id = projectfiles_projectID";
And to my surprise, the LEFT JOIN didn't seem to pick up anything at all.
Code:
$sql = "SELECT id,name,userID FROM projects";
$sql .= " LEFT JOIN".
" (SELECT
projectfiles.id as projectfiles_id,
projectfiles.fileID as projectfiles_fileID,
projectfiles.projectID as projectfiles_projectID
FROM projectfiles
) AS projectfiles".
" ON projects.id = projectfiles_projectID";
$res = mysql_query($sql);
if(!$res) die(mysql_error());
if(mysql_num_rows($res) > 0)
{
$rownum = 0;
while($row = mysql_fetch_assoc($res))
{
print_r($row);
echo "<br/><br/>";
$rownum++;
}
}
Output:
Which is weird because there is only one row in projects but 3 in projectfiles with that projectID... what am I doing wrong?
To select only from the projectfiles table:
$sql = "SELECT projectfiles.*,
projects.id as projects_id
FROM projects";
// rest of the code is the same
Update
$sql = "SELECT projectfiles.* FROM projects";
// rest of the code is the same
Use short form of the query:
$sql = "SELECT projects.id,projects.name,projects.userID FROM projects LEFT JOIN
projectfiles ON projects.id = projectfiles.projectID";
SELECT p.*, pf.id, pf.fileId
FROM projects p LEFT JOIN projectfiles pf
on p.id = pf.projectID
You can use "as" to do as you will then. No need for a subselect.
$sql = "SELECT p.id,p.name,p.userID FROM projects p";
$sql .= " LEFT JOIN".
" projectfiles pf ".
" ON p.id = p.projectID";
$sql = "SELECT prj.id as prjId,
prj.name as prjName,
prj.userID as prjUid,
pf.id as pfId,
pf.fileID as pfFileId,
pf.projectID as pfProjecId
FROM projects as prj
LEFT JOIN projectfiles AS pf
ON prj.id = pf.projectID";
Related
for the past few hours, I have been trying to find a simple method of while loop echoing information from multiple tables at once. I'd like to say I've not pulled all my hair out looking, but I have.
Here is one mysqli query to get the following fields from CUSTOMER
$tid = $_SESSION['user_id']; // "id" is 1 for example
$query = "SELECT * FROM `CUSTOMER` WHERE user_id = {$tid}";
$results = mysqli_query($dbconnection, $query);
while ($row = mysqli_fetch_array($results)) {
echo $row['user_id'] . "<br><br>";
echo $row['c_fname'] . "<br>";
echo $row['c_sname'] . "<br>";
};
Here is another mysqli query to get the following fields from SALE
$query = "SELECT * FROM `SALE` WHERE user_id = {$tid}";
$results = mysqli_query($dbconnection, $query);
while ($row = mysqli_fetch_array($results)) {
echo $row['s_date'] . "<br>";
echo $row['s_total'] . "<br>";
};
Could someone possibly show me how I can get both of these tables in one query so that echoing both tables information is possible at the same time instead of separately. I am not fussed how it is done, As long as it gets all from both tables for echoing purpose, that is good.
You can do it by using LEFT JOIN like this.
SELECT column_name(s)
FROM table1
LEFT JOIN table2 ON table1.column_name = table2.column_name;
And this is your code.
$query = "SELECT * FROM `CUSTOMER` LEFT JOIN `SALE` ON `SALE`.user_id=`CUSTOMER`.user_id WHERE `SALE`.user_id={$tid}";
$results = mysqli_query($dbconnection, $query);
while ($row = mysqli_fetch_array($results)) {
echo $row['user_id'] . "<br><br>";
echo $row['c_fname'] . "<br>";
echo $row['c_sname'] . "<br>";
echo $row['s_date'] . "<br>";
echo $row['s_total'] . "<br>";
}
For more info read this,
https://www.w3schools.com/sql/sql_join_left.asp
I hope this helps.
EDITED
This is for joining 3 tables,
SELECT column_name(s)
FROM table1
LEFT JOIN table2 ON table1.column_name = table2.column_name;
LEFT JOIN table3 ON table1.column_name = table3.column_name;
In your code.
SELECT * FROM `CUSTOMER`
LEFT JOIN `SALE` ON `CUSTOMER`.user_id = `SALE`.user_id
LEFT JOIN `PRODUCTS` ON `CUSTOMER`.user_id = `PRODUCTS`.user_id
WHERE `SALE`.user_id={$tid};
As variable.
$query = "SELECT * FROM `CUSTOMER` LEFT JOIN `SALE` ON `CUSTOMER`.user_id = `SALE`.user_id LEFT JOIN `PRODUCTS` ON `CUSTOMER`.user_id = `PRODUCTS`.user_id WHERE `SALE`.user_id={$tid}";
You can use the following code and will help u solve Ur problem
$query = "SELECT C.*,S.* FROM CUSTOMER C,SALES S
WHERE C.user_id={$tid}
and C.user_id=S.user_id;
while ($row = mysqli_fetch_array($results)) {
echo $row['C.user_id'] . "<br><br>";
echo $row['C.c_fname'] . "<br>";
echo $row['C.c_sname'] . "<br>";
echo $row['S.s_date'] . "<br>";
echo $row['S.s_total'] . "<br>";
};
You can simply join the tables to get your expected result as shown below.
$query = "SELECT c.user_id, c.c_fname, c.c_sname, s.s_date, s.s_total FROM `CUSTOMER` AS c INNER JOIN `SALE` AS s ON c.user_id = s.user_id WHERE c.user_id = {$tid}";
Joining 3 tables example
$query = "SELECT *
FROM `CUSTOMER` AS c
INNER JOIN `SALE` AS s ON c.user_id = s.user_id
INNER JOIN `PRODUCTS` AS p ON p.product_id = s.product_id
WHERE c.user_id = {$tid}";
I want to build a search engine for a webpage. I use the code below. The problem is, that I have to build the queries from different strings and if the system searches for matching in strings, quote marks are needed.
$sql = "SELECT TIT,VNEV,KNEV,NEME,MEGY,LCVAR,APOLG FROM TORZS LEFT OUTER JOIN VEGZETTSEG ON TORZS.ID = VEGZETTSEG.ID LEFT OUTER JOIN SZTAPASZTALAT ON TORZS.ID = SZTAPASZTALAT.ID LEFT OUTER JOIN SZAKTANFOLYAM ON TORZS.ID = SZAKTANFOLYAM.ID LEFT OUTER JOIN INFORM ON TORZS.ID = INFORM.ID WHERE ";
for ($i = 0;$i < count($searchcategs);$i++) {
$sql = $sql . $searchcategs[$i];
$sql = $sql . " = ";
$sql = $sql . $searchvals[$i];
$sql = $sql . " ";
}
An alternative version:
$sql = "SELECT TIT,VNEV,KNEV,NEME,MEGY,LCVAR,APOLG FROM TORZS LEFT OUTER JOIN VEGZETTSEG ON TORZS.ID = VEGZETTSEG.ID LEFT OUTER JOIN SZTAPASZTALAT ON TORZS.ID = SZTAPASZTALAT.ID LEFT OUTER JOIN SZAKTANFOLYAM ON TORZS.ID = SZAKTANFOLYAM.ID LEFT OUTER JOIN INFORM ON TORZS.ID = INFORM.ID WHERE ";
for ($i = 0;$i < count($searchcategs);$i++) {
$sql = $sql . $searchcategs[$i];
$sql = $sql . " = '";
$sql = $sql . $searchvals[$i];
$sql = $sql . "' ";
}
None of them seems to work, I got
SELECT TIT,VNEV,KNEV,NEME,MEGY,LCVAR,APOLG FROM TORZS LEFT OUTER JOIN VEGZETTSEG ON TORZS.ID = VEGZETTSEG.ID LEFT OUTER JOIN SZTAPASZTALAT ON TORZS.ID = SZTAPASZTALAT.ID LEFT OUTER JOIN SZAKTANFOLYAM ON TORZS.ID = SZAKTANFOLYAM.ID LEFT OUTER JOIN INFORM ON TORZS.ID = INFORM.ID WHERE
for the query even though the searchcateg and searchval arrays are existing and not empty.
I don't understand why following query is not return anything. If I change the query then it's return result.
what I'm doing now (No output)
$msg = array();
$getSearch = "SELECT contact_details . * , company.company_name, users.nickname FROM contact_details LEFT JOIN users ON users.user_id = contact_details.user_id LEFT JOIN company ON company.cid = contact_details.cid WHERE";
if(!empty($ad_company)){
$getSearch .= "company.company_name LIKE '$ad_company%' ";
}
$getSearch = mysql_query($getSearch);
while($searchResult = mysql_fetch_array($getSearch)){
$msg[] = $company = $searchResult['company_name'] . "<br/>";
}
echo json_encode($msg);
Change Code(Working)
$msg = array();
$getSearch = "SELECT contact_details . * , company.company_name, users.nickname FROM contact_details LEFT JOIN users ON users.user_id = contact_details.user_id LEFT JOIN company ON company.cid = contact_details.cid WHERE company.company_name LIKE '$ad_company%'";
//$msg[] = empty($ad_company) ? "empty company" : "not empty company"; //for checking and field has value
/*if(!empty($ad_company)){
$getSearch .= "company.company_name LIKE '$ad_company%' ";
}*/
$getSearch = mysql_query($getSearch);
while($searchResult = mysql_fetch_array($getSearch)){
$msg[] = $company = $searchResult['company_name'] . "<br/>";
}
echo json_encode($msg);
Maybe becouse you don't have a space between WHERE and company?
Try this
As answer by Mitja , you have missed the space between WHERE and company
$getSearch = "SELECT contact_details . * , company.company_name, users.nickname
FROM contact_details
LEFT JOIN users ON users.user_id = contact_details.user_id
LEFT JOIN company ON company.cid = contact_details.cid ";
if(!empty($ad_company)){
$getSearch .= " WHERE company.company_name LIKE '$ad_company%' ";
}
EDITED
$getSearch = "SELECT contact_details . * , company.company_name, users.nickname
FROM contact_details
LEFT JOIN users ON users.user_id = contact_details.user_id
LEFT JOIN company ON company.cid = contact_details.cid
WHERE 1=1 ";
if(!empty($ad_company)){
$getSearch .= " AND company.company_name LIKE '$ad_company%' ";
}
I have removed the WHERE from your $getSearch query and added to the one we are appending
$getSearch = "SELECT contact_details . * , company.company_name, users.nickname FROM contact_details LEFT JOIN users ON users.user_id = contact_details.user_id LEFT JOIN company ON company.cid = contact_details.cid";
if(!empty($ad_company)){
$getSearch .= " WHERE company.company_name LIKE '$ad_company%' ";
}
in future if you face problems like these always try to print only sql query before querying it with db.. this way you will get to see as if your query is correct or not
I have a php code that use a mySQL query in it.
tables users and conversation and main_profile have true values to select after this query but query return nothing.
$sqlQuer =
"SELECT `conversation`.from,`conversation`.text, `main_profile`.nik_name, `users`.id
FROM `conversation`
INNER JOIN `users` ON(`users`.username = `conversation`.to )
INNER JOIN `main_profile` ON(`users`.id = `main_profile`.user_id)
WHERE `conversation`.to = '".$to."'
AND `conversation`.read = '0'";
$result = mysql_query( $sqlQuer) or die (mysql_error());
while($row = mysql_fetch_array($result))
{
echo $row[0] . "#TEXT#" . $row[1]. "#TEXT#" . $row[2] . "#CON#";
$ids[] = $row['id'];
}
any Idea ?
Query was solved with this change that First INNER JOIN changed to LEFT JOIN and second changed to RIGHT JOIN.
say if I have the query select users.user_id, users.fname, users.lname, bios.bio, groups.groupid from users LEFT JOIN bios on users.user_id = bios.userid then I want to add another table on a condition then add a where statement at the end. The problem is because when I bind the param it said 'number of variables doesn't match the number of variables in the prepare statement'. How would I solve this? Cheers. Example:
$info = "select users.user_id, users.fname, users.lname, bios.bio, groups.groupid from users LEFT JOIN bios on users.user_id = bios.userid";
$content = $members->prepare($info);
if ($_GET['where'] == 'requests') $info .= "LEFT JOIN requests on users.user_id = requests.receiver";
else if ($_GET['where'] == 'referrals') $info .= "LEFT JOIN referrals on users.user_id = referrals.receiver";
$info .= "where users.user_id = ?";
$content->bind_param('s', $_SESSION['token'][1]);
$content->execute();
You're changing the SQL string after preparing it. Don't do that. Do it like this instead:
$info = "select users.user_id, users.fname, users.lname, bios.bio, groups.groupid from users LEFT JOIN bios on users.user_id = bios.userid";
if ($_GET['where'] == 'requests') $info .= " LEFT JOIN requests on users.user_id = requests.receiver";
else if ($_GET['where'] == 'referrals') $info .= " LEFT JOIN referrals on users.user_id = requests.receiver";
$info .= " where users.user_id = ?";
$content = $members->prepare($info);
$content->bind_param('s', $_SESSION['token'][1]);
$content->execute();
Edit: Also, make sure your SQL fragments are separated with spaces where necessary; the .= operator doesn't automatically add a space for you.