I have 3 tables I need to join. The contracts table is the main table, the 'jobs' and 'companies' table are extra info that can be associated to the contracts table.
so, since I want all entries from my 'contracts' table, and the 'jobs' and 'companies' data only if it exists, I wrote the query like this....
$sql = "SELECT * FROM contracts
LEFT JOIN jobs ON contracts.job_id = jobs.id
LEFT JOIN companies ON contracts.company_id = companies.id
ORDER BY contracts.end_date";
Now how would I output this in PHP? I tried this but kept getting an undefined error "Notice: Undefined index: contracts.id"...
$sql_result = mysql_query($sql,$connection) or die ("Fail.");
if(mysql_num_rows($sql_result) > 0){
while($row = mysql_fetch_array($sql_result))
{
$contract_id = stripslashes($row['contracts.id']);
$job_number = stripslashes($row['jobs.job_number']);
$company_name = stripslashes($row['companies.name']);
?>
<tr id="<?=$contract_id?>">
<td><?=$job_number?></td>
<td><?=$company_name?></td>
</tr>
<?
}
}else{
echo "No records found";
}
Any help is appreciated.
The column names will not be prefixed like this - and with each table having a column called "id" you could be in trouble. You should explicitly identify the columns you want returned rather than using "select *", and you then just retrieve the column by name un prefixed (e.g. $row['job_number']).
The below would solve you problem.
$sql = "SELECT contracts.id AS contract_id, jobs.job_number, companies.name FROM contracts
LEFT JOIN jobs ON contracts.job_id = jobs.id
LEFT JOIN companies ON contracts.company_id = companies.id
ORDER BY contracts.end_date";
Your problem is likely to be realted to the fact you are using two tables with the field id this is why you should select them as an alias using the mysql as clause.
You may also want to look into using a naming convention for your fields and sticking with it. For example, check out the theory of Hungarian Notation, this would stop issues like this from arrissing.
Related
So I'm trying to implement a JOIN in my PHP but I don't know how to include the WHERE clause with JOIN in my query.
I'm trying to do:
SELECT SpecialFacts.ConservationStatus, SpecialFacts.Reproduction, SpecialFacts.Length, Habitat.Type, Habitat.located
FROM SpecialFacts
INNER JOIN Habitat ON SpecialFacts.SpeciesID=Habitat.SpeciesID
WHERE SpeciesID="G. cuvier"
Basically I'm trying to make sure the join happens on the tables where the SpeciesID is G. cuvier but everything I have tried so far doesn't work and the error it is giving me now is "Column SpeciesID in where clause is ambiguous".
Here is my relevant PHP code:
<?php
include 'connect.php';
$result = mysqli_query($connect,"SELECT SpecialFacts.ConservationStatus, SpecialFacts.Reproduction, SpecialFacts.Length, Habitat.Type, Habitat.located FROM SpecialFacts INNER JOIN Habitat ON SpecialFacts.SpeciesID=Habitat.SpeciesID WHERE SpeciesID='G. cuvier'") or die("fail" . mysqli_error($connect));
$i = 0;
while($row = mysqli_fetch_array($result))
{
echo $row[$i];
$i = $i + 1;
}
Column SpeciesID exists in both tables, so it doesn't know which need to be compared to value given as G. cuvier. As you are writing every column name as table name with dot(.), the same should be in where condition column SpecialFacts.SpeciesID = "G. cuvier".
So query should be like:
SELECT SpecialFacts.ConservationStatus, SpecialFacts.Reproduction, SpecialFacts.Length, Habitat.Type, Habitat.located
FROM SpecialFacts
INNER JOIN Habitat ON SpecialFacts.SpeciesID=Habitat.SpeciesID
WHERE SpecialFacts.SpeciesID="G. cuvier"
It's not giving you that error because you're using WHERE incorrectly. It's giving you that error because there are multiple tables in your query that have a column with that name, hence the "ambiguous". You just need to disambiguate it by adding the table name to the identifier.
WHERE SpecialFacts.SpeciesID="G. cuvier"
or
WHERE Habitat.SpeciesID="G. cuvier"
Since you're inner joining the tables on that column, either table should work for the WHERE clause. I would suggest using the smaller table for performance reasons, but honestly I'm not 100% certain if it will matter or not. You can do EXPLAIN on each one to see how they compare.
Use below query instead
SELECT SpecialFacts.ConservationStatus, SpecialFacts.Reproduction, SpecialFacts.Length, Habitat.Type, Habitat.located
FROM SpecialFacts INNER JOIN Habitat
ON SpecialFacts.SpeciesID=Habitat.SpeciesID
WHERE SpecialFacts.SpeciesID='G. cuvier'
I have used single quote and used column name with table name.
So i fetch my data from two tables in my php and encode it in one json object. I got everything i needed except that it doubles the display. And my teamone is located in the matches tables. instead of starting from array 0, it starts after the schedules tables. Which is array 7. I dont know why this happen.
Here is my php.
$sql = "SELECT * from schedule, matches;";
$con = mysqli_connect($server_name,$mysql_user,$mysql_pass,$db_name);
$result = mysqli_query($con,$sql);
$response = array();
while($row=mysqli_fetch_array($result))
{
array_push($response, array("start"=>$row[4],"end"=>$row[5],"venue"=>$row[6], "teamone"=>$row[8], "teamtwo"=>$row[9],
"s_name"=>$row[17]));
}
echo json_encode (array("schedule_response"=>$response));
mysqli_close($con);
?>
Here is my display. As you can see there are four displays but in my database it only has 2. It doubles the display. How do i fix this? Thanks
{ "schedule_response":[
{"start":"2016-11-10 00:00:00","end":"2016-11-04 00:00:00","venue":"bbbb","teamone":"aaa","teamtwo":"bbb",
"s_name":"hehehe"},
{"start":"2016-11-23 00:00:00","end":"2016-11-24 00:00:00","venue":"bbbbbbbb","teamone":"aaa","teamtwo":"bbb",
"s_name":"hehehe"},
{"start":"2016-11-10 00:00:00","end":"2016-11-04 00:00:00","venue":"bbbb","teamone":"ehe","teamtwo":"aha",
"s_name":"aaa"},
{"start":"2016-11-23 00:00:00","end":"2016-11-24 00:00:00","venue":"bbbbbbbb","teamone":"ehe","teamtwo":"aha",
"s_name":"aaa"}]}
I need to get the teamone, teamtwo and s_name values from the matches while i need the start, end and the venue from the schedule table in one query.
Schedule table
Matches Table
Because of your SQL query, you should not forget to perform some form of a grouping (the way you select results from both table defines that):
$sql = "SELECT * from schedule s, matches m GROUP BY s.id"; //I assume that your table schedule has an `id`
Or, you can rework the query to be more readable:
$sql = "SELECT s.*, m.* FROM schedule s
INNER JOIN matches m ON m.schedule_id = s.id
GROUP BY s.id"; //I assume that you have such database design that you have defined foreign key on table `matches`.
Of course, the INNER JOIN above could be LEFT OUTER JOIN - it all depends on your database design.
I think it is the problem with mysqli_fetch_array().
Can you please change mysqli_fetch_array() to mysqli_fetch_assoc()
I have to select data from multiple tables based on single key value. I have one table called maintable where I will get all the ids from, and i have another 10 tables in the same database which have maintable.id as a foreign key. Now I have to retrieve data from the 10 tables where maintable.id matches in one single table.
The code I have tried is:
$sql = select id from maintable;
$runsql = mysql_query($sql);
while($sqlRow = mysql_fetch_array($runsql ,MYSQL_ASSOC)) {
for($i=1;$i<=10(This is another table count);$i++) {
$servSql = "select * from table.$i where ref_id = ".$sqlRow['id'];
$runServerSql = mysql_query($servSql);
while($serverRow = mysql_fetch_array($runServSql,MYSQL_ASSOC)) {
}
}
}
Try something like this in a join:
SELECT * FROM maintable m
INNER JOIN othertable o
ON m.id = o.id
That will select from both tables using an inner join ON the id column. You may want to look up a basic SQL tutorial to learn the basic types of joins you can use. Good luck!
I have multiple tables and I want to access the fields in a specific table. Here are the table schemas:
Each tbl_acct has one tbl_unit. A tbl_unit has many tbl_groups and a tbl_groupcontact consist of the contacts and the related group. Every time I log in, I set a session where $_SESSION['unitid'] = $row['unitid'];.
What I wanted to do is to access the fields in the tbl_contacts. For now my code is here:
$data = $conn->prepare("SELECT * FROM tbl_groups LEFT JOIN tbl_groupcontact ON tbl_groups.id=tbl_groupcontact.group_id WHERE tbl_groups.unitid = ?");
$data->execute(array($_SESSION['unitid']));
foreach ($data as $row) {
echo $row['fname'] . " " . $row['lname']. "<br />";
}
As you can see, I can related the tbl_groups and tbl_groupcontact in my code however, I can't get the fields in the tbl_contacts. Am I missing something here? Any help would be much appreciated.
You need to join another table.
SELECT tbl_contacts.*
FROM tbl_groups
INNER JOIN tbl_groupcontact ON tbl_groupcontact.group_id = tbl_groups.id
INNER JOIN tbl_contacts ON tbl_contacts.id = tbl_groupcontact.contact_id
WHERE tbl_groups.unitid = ?
No need for (slower) LEFT JOIN btw - use it when you want to retrieve records from (left-side) table even when there's no match found in joined (right-side) table (it's columns will be filled with nulls in this case).
Basically I have 2 SQL queries from 2 different databases and I am trying to compare where they are equal and then join together the other information for that value. My first query contains an id and a product name, my second query contains a product name and components. So I'm trying to join them on the product name and then show the other two bits of information with them. The db I selected is being used in the second query. Any idea what I should do?
So far I have this, which only seems to show one result:
$catid = mysql_query("Select a.entry_id, b.cat_name from blog.exp_category_posts a inner join blog.exp_categories b on a.cat_id=b.cat_id where b.Group_ID = 3");
$results = mysql_query("Select a.name, c.product from wr_scientific a inner join wr_scientific_products b on a.id=b.scienc_id Join xcart_products c on b.prod_id=c.productid LIMIT 1000");
while($row1 = mysql_fetch_array($catid)){
$row2= explode("™", $row1['cat_name']);
$row3= explode("®", $row2[0]);
while($row = mysql_fetch_array($results)){
$rowpro = explode("™", $row['product']);
$rowprod = explode("®", $rowpro[0]);
if($rowprod[0] == $row3[0]){
echo $rowprod[0].$row['name'].$row1['entry_id'];
}
}
}
Thanks for any help
If the two databases are located on the same instance of MySQL (~ same machine), then you can refer to a table in say db2 from (say) db1 by prefixing the table name with the database name.
E.g:
USE db1 ;
SELECT
db1.table_in_db1.id, -- you can specify the database name here, but
table_in_db2.id, -- there is no ambiguity, the database name is optional
field_in_table_in_db2 -- the same way the table name is optionnal when there is no ambiguity
FROM
db1.table_in_db1 -- database name is optionnal here, current database is assumed
JOIN
db2.table_in_db2
ON ...