Selecting * from two tables using php and mySQL [duplicate] - php

This question already has answers here:
How to resolve ambiguous column names when retrieving results?
(11 answers)
Closed 2 years ago.
I have two tables, one is projects, and the other is users.
PROJECTS table
ID | USER_ID | NAME
-------------------------------------
80 | 1 | ABC Co.
82 | 2 | XYZ Inc.
USERS table
ID | FIRSTNAME | LASTNAME
-------------------------------------
1 | Joe | Namath
2 | Jimmy | Fallon
What I want is to write a query such as:
SELECT * FROM PROJECTS, USERS WHERE PROJECTS.USER_ID=USERS.ID AND FIRSTNAME = "Joe"
I can successfully run the query in php, but when I attempt to access the results, I don't get what I want. I understand why, but I can't figure out a way to correct it. For example:
$row = mysqli_fetch_query($awesomeDatabaseLink);
echo $row['ID]; //returns '1' and I really wanted '80'
I get it. The two tables have fields with the same name, but it's not the same data. MySQL returns its best guess at what I so ambiguously asked for. However, I have also tried:
echo $row['PROJECTS.ID']; //returns an empty string.
I should mention that I desperately need "*" from both tables. The Projects table has dozens and dozens of fields (not my design, and re-engineering the database is out-of-scope). The Users table is also very extensive, so listing each field individually is much more impractical than it would appear by looking at my example tables.
Any suggestions?
SH

The quickest fix is to assign a unique column alias for the expression (in this case just a simple column reference).
When you do that, you will need to qualify the * with the table name or alias. If you want to return all of the columns from both tables, you will need to included a * for each table.
Also, ditch the old-school comma operator for the join operation, and use the JOIN keyword instead. And qualify all column references. For example:
SELECT PROJECTS.*
, USERS.*
, PROJECTS.ID AS MY_PROJECTS_ID
FROM PROJECTS
JOIN USERS
ON USERS.ID=PROJECTS.USER_ID
AND USERS.FIRSTNAME = "Joe"
The assigned alias MY_PROJECTS_ID will be the name of the column in the result set, so you reference that column by the assigned alias.
This assumes that there are no other columns being returned with the name MY_PROJECTS_ID.
Anytime there are two (or more) columns in the resultset that have the same name, you'll only get one of those columns referencing it by name.

I'd suggest you to use alias. That'd make things less ambiguous.
Try this:
SELECT
PROJECTS.ID AS project_id,
USER_ID,
NAME,
USERS.ID AS user_id,
FIRSTNAME,
LASTNAME
FROM PROJECTS, USERS
WHERE PROJECTS.USER_ID=USERS.ID AND FIRSTNAME = "Joe"
And then:
echo $row['project_id']; //returns Project id
Hope this helps.

When you select stuff from multiple tables you should always qualify the names (give the full path, like table.column). If two tables share a column name then you need to give them different names.
SELECT u.ID AS UserId,
u.FIRSTNAME AS FirstName,
u.LASTNAME AS LastName,
p.ID AS ProjectId,
p.NAME AS ProjectName
FROM USERS AS u
JOIN PROJECTS AS p ON p.USER_ID = u.ID
WHERE u.FIRSTNAME = "Joe"
If you want to get every column, but some of their names clash, then you can just rename the ones that clash, like so:
SELECT *,
u.ID as USERID,
p.ID as PROJECTID
FROM USERS AS u
JOIN PROJECTS AS p ON p.USER_ID = u.ID
WHERE u.FIRSTNAME = "Joe"

Hope this will help you.
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Using single SQL</title>
<style>
table,td,th
{
padding:10px;
border-collapse:collapse;
font-family:Georgia, "Times New Roman", Times, serif;
border:solid #ddd 2px;
}
</style>
</head>
<body>
<table align="center" border="1" width="100%">
<tr>
<th>product id</th>
<th>product name</th>
<th>category name</th>
</tr>
<?php
mysql_connect("localhost","root");
mysql_select_db("dbtuts");
$res=mysql_query("SELECT c.* , p.* FROM tbl_categories c,tbl_products p WHERE c.cat_id=p.cat_id");
while($row=mysql_fetch_array($res))
{
?>
<tr>
<td><p><?php echo $row['product_id']; ?></p></td>
<td><p><?php echo $row['product_name']; ?></p></td>
<td><p><?php echo $row['cat_name']; ?></p></td>
</tr>
<?php
}
?>
</table>
</body>
</html>
follow this [link] (http://www.codingcage.com/2014/12/fetch-data-from-multiple-tables-in-php.html)!

Related

Join two tables using php

I have no idea with joins and I am really having a trouble getting the logic. Can anyone please help me?
Here is my table Announcements:
AnnouncementID Subject Header Status
---------------------------------------------------
1 Peter Header 2 Publish
2 2x2 Header 3 Draft
3 Resignation Header 4 Publish
And here is another table ReadAnnouncements:
AnnouncementID Username Status
---------------------------------------------
1 User 1 Read
2 User 2 Read
2 User 3 Read
I want my result to be
AnnouncementID Username Status Header Subject
---------------------------------------------------------------
1 User 1 Read Peter Header 2
2 User 2 Read 2x2 Header 3
2 User 3 Read 2x2 Header 3
Please teach me how I am really confused been trying this for two days already.
<?php
$sql=" SELECT a.AnnouncementID,a.Created,r.Username,a.Status,a.Header,a.Body from Announcements a join ReadAnnouncements r using(AnnouncementID) WHERE a.Status = 'Publish'";
$result = mysqli_query( $conn,$sql);
while($rows = mysqli_fetch_array($result)){
$time = date('h:i:s a',strtotime($rows['Created']));
$date = date('Y-m-d',strtotime($rows['Created']));
if($rows['ReadStatus'] == 'Unread'){
echo '
<tr class="'.$rows['Status'].'clickable-row" >
<strong><td class="view-message dont-show"><div>'.$rows['Header'].'</div></td>
<td class="view-message "><a href="ViewAnnouncement.php?view_id='.$rows['AnnouncementID'].'" style="text-decoration: none" class="text-dark" ><div>'.substr($rows['Body'],0,90).'</div></a></td>
<!--<td class="view-message inbox-small-cells"><i class="fa fa-paperclip"></i></td>-->
<td class="view-message text-right"><div><h6>'.$time.''.'<br>'.''.$date.'</h6></div></td></strong></tr>
';
}else{
echo '<strong>
<tr class="'.$rows['Status'].'clickable-row" >
<strong><td class="view-message dont-show"><div>'.$rows['Header'].'</div></td>
<td class="view-message "><a href="ViewAnnouncement.php?view_id='.$rows['AnnouncementID'].'" style="text-decoration: none" class="text-dark" ><div>'.substr($rows['Body'],0,90).'</div></a></td>
<!--<td class="view-message inbox-small-cells"><i class="fa fa-paperclip"></i></td>-->
<td class="view-message text-right"><div><h6>'.$time.''.'<br>'.''.$date.'</h6></div></td></strong></tr>
</strong>';
}
}
?>
I want to select all rows from table announcements that are only Published and classify them if they are read or unread based on username and announcement id.
You can use the below query to get the result.
select a.AnnouncementID,r.Username,r.Status,a.Header,a.Subject
from Announcements a
join ReadAnnouncements r on r.AnnouncementID=a.AnnouncementID
Joins are pretty easy, check this explanation.
In your case, you can do something like this:
SELECT A.AnnouncementID, A.Username, R.Status, A.Header, A.Subject FROM Announcements A join ReadAnnouncements R USING(AnnouncementID)
You can use inner join. The INNER JOIN keyword selects records that have matching values in both tables.
SELECT a.AnnouncementID,r.Username,r.Status,a.Header,a.Subject
from Announcements a
join ReadAnnouncements r using(AnnouncementID)
Use JOIN clause to combine rows from two or more tables in a database, based on a related column between them ( in your case, AnnouncementID ).
When combine data from 2 tables, you have a few combinations possible:
(INNER) JOIN: Returns records that have matching values in both tables
LEFT (OUTER) JOIN: Return all records from the left table, and the matched records from the right table
RIGHT (OUTER) JOIN: Return all records from the right table, and the matched records from the left table
FULL (OUTER) JOIN: Return all records when there is a match in either left or right table
(source: https://www.w3schools.com/sql/sql_join.asp)
Using your database schema, you should use:
select * from Announcements as A INNER JOIN ReadAnnouncements as RA ON A.AnnouncementID RA.AnnouncementID
You don't mention which DBMS you are using, so SQL query above may differ.

bring data from 2 tables mysql and display them

I have 2 tables. Table user_job(id, title, expires) and table user_job_business(id, title, expires). The first table holds jobs posted by users and the second table holds jobs posted by companies. All I want is to display all jobs from users and companies in the same page the one under the other each job in its own table. How can I modify my code to do this? This is my code dipslaying jobs from users one under the other.
<?php
$get_myjobs = mysql_query("select * from `user_job` ");
while($run_job = mysql_fetch_array($get_myjobs )){
$user_job_id = $run_job['id'];
$user_job_title = $run_job['title'];
$user_job_expires = $run_job['expires'];
echo"<table> <td>$user_job_title</td> <td>$user_job_expires</td> </table>";
}
?>
you can use union or union all:
$get_myjobs = mysql_query("select id, title, expires from `user_job` union all select id, title, expires from `user_job_business`");
the difference between union and union all, union remove redundancy or repeated rows.
You can use union in your case, but I would recommend you reorganize your structure and make 1 table instead of 2. It will give you better schema and good performance.
it | title | expires | role_id
where role_id - identifier to user,company

PHP - Getting wrong result when selecting from two tables

I have been trying to get some results when selecting combo boxes.
here is my query:
$strSQL = "SELECT * FROM studentresult,student where studentresult.studentid=student.id and student.class='$classes' and term='$term'and studentresult.studentid=student.id and year='$year' ";
This query is returning all the studentresult.id = 2 where studentresult.id is primary.
This is the php code:
<td><div align="center"><?=$objResult["id"];?></div></td>
<td><div align="center"><?=$objResult["studentid"];?></div></td>
<td><?=$objResult["subjectid"];?></td>
<td><?=$objResult["marks"];?></td>
<td><div align="center"><?=$objResult["term"];?></div></td>
<td align="right"><?=$objResult["year"];?></td>
<td align="right"><?=$objResult["rank"];?></td>
The id is taken from student table rather than being taken from studentresult table. Can someone help me with this.
EDIT 1:
The id is present in both tables
EDIT 2:
Student result:
id| StudentID| SubjectID| Marks| Rank| Term| Year
Student:
id| Roll Num| class| Name| Surname
Thanking You In Advance
Bhaamb
$strSQL = "SELECT *,studentresult.id as stid FROM studentresult,student where studentresult.studentid=student.id and student.class='$classes' and term='$term'and studentresult.studentid=student.id and year='$year' ";
Then
<div align="center"><?=$objResult["stid"];?></div>
You Better specify the column names instead of (*) from both the tables alias the column names to avoid column name conflicts if both are same and also try to use Join(Inner or Left) based on the need.
for example, some thing like this:
SELECT S.id AS student_id, SR.id as StudentResultId, S.class, s.year
FROM studentresult AS SR
INNER JOIN student AS S
WHERE SR.studentid=S.id and S.class='$classes' and s.term='$term'and SR.studentid=s.id and s.year='$year'
First of all, why do you use this twice in the where clause?
studentresult.studentid=student.id
Please define all needed columns explicitly while joining tables having the same column names, e.g.
SELECT studentresult.id as sr_id, student.id as s_id ... FROM ...
and change it in your php code:
<?=$objResult["sr_id"];?>

Why isn't this easy join working? (mysql)

I have two tables, classified and fordon.
classified table:
classified_id (PK)
etc...
fordon table:
id (PK)
classified_id (FK)
I try to use this code:
SELECT * FROM classified, fordon WHERE classified.ad_id IN ('$solr_id_arr_imploded') AND classified.classified_id=fordon.classified_id
BTW, the array is a set of ad_id:s returned from solr, never mind that, that is not the problem here...
Then I use mysql_fetch_array in a while-loop to display all the results:
while($row = mysql_fetch_array($qry_result)){
but when I try to echo something which is inside the table fordon, then the index can't be found error appears. But whatever is inside the table classified works to echo!
Any ideas?
Thanks
UPDATE
while($row = mysql_fetch_array($qry_result)){
echo $row['type']; // This doesn't work, because the 'type' column is inside the 'fordon' table
echo $row['headline']; // This does work because it's inside 'classified' table.
Does this help?
SELECT *
FROM classified c
INNER JOIN fordon f ON c.classified_id=f.classified_id
WHERE classified.ad_id IN ('$solr_id_arr_imploded');
Also, its generally not a good idea to use: SELECT *. Its better to either select only the elements you want or use the * in context of the table you are getting all from, e.g.
SELECT classified.*
FROM classified c
INNER JOIN fordon f ON c.classified_id=f..classified_id
WHERE classified.ad_id IN ('$solr_id_arr_imploded');
When you do joins with a blanket * you get every field in all tables.

Join tables - MySQL & PHP

I'm trying to join two tables. The first table has a list of 11 items which are 'site_names' with an auto id field of 'id'. The second table that I want to connect has an auto id field of 'desc_id' and another field of 'descriptions'. This second table currently has 3 rows of data that I want displayed only for id 1 in table 1.
So, I want to accomplish is to connect the first site in table one with an id of '1' to the entire second table.
I can't seem to figure out how connect only the first entry(id=1) in table 1 to all the rows in table 2 (tb.1->id->1 to tbl.2->desc_id->1,2,3).
I hope that made sense. Any help would be great. Thanks
Try:
select site_name, descriptions
from table_1
inner join table_2
on 1 = 1
where table_1.site_id = 1
This should join give you what you want.
OK - based on the comment, I'm guessing what you want is:
site1 | desc1 | desc2 | desc3
all on one row. This is a bit trickier - particularly if you want it to remain open to an arbitrary number of descriptions. For just 3 (or, really, any limited subset, but as the number goes up, it gets ugly), you could do:
select site_name, t2.desc, t3.desc, t4.desc
from table_1
inner join table_2 t2
on t2.desc_id = 1
inner join table_2 t3
on t3.desc_id = 2
inner join table_2 t4
on t4.desc_id = 3
where site_id = 1
This kind of stuff is highly irregular though. It seems to me like something about your schema is probably not quite right to generate this sort of requirement.
Here is the query:
<?php
$mysql = new mysqli('localhost', 'root', 'root') or die('counld not connect');
$result = $mysql->query("SELECT ajax_demo.explore.site_name, anthony1.property.descriptions FROM ajax_demo.explore INNER JOIN anthony1.property ON ajax_demo.explore.id = anthony1.property.desc_id") or die($mysql->error);
if($result)
{
while($row = $result->fetch_object())
{
$id = $row->id;
$siteName = $row->site_name;
$siteDescription = $row->site_description;
echo "$siteName";
echo "$siteDescription";
}
}
?>
I may be missing something here, but it sounds to me like you need to add a foreign key to the Site table. If I understand your question correctly, your tables should look something like this:
Site
- SiteID
- DescriptionID
- SiteName
Description
- DescriptionID
- Description
Then your query to get Sites and their associated Descriptions would look like this:
SELECT
s.SiteName,
d.Description
FROM
Site s INNER JOIN Description d
ON s.DescriptionID = d.DescriptionID
This table structure assumes that multiple Sites share single Descriptions (as per your posted question).

Categories