Fetching all Data from Multiple tables based on Single id - php

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!

Related

MySQL two conditions for two tables

I have a mysql query:
$query5 = mysql_query("SELECT * FROM `pages` WHERE (`id`='$switch' AND `rand`='$randID' AND `email`!='".$_SESSION['user']."') ");
And second:
$query5 = mysql_query("SELECT * FROM `pages_admin` WHERE (`pId`='$switch' AND `rand`='$randID' AND `admin`!='".$_SESSION['user']."') ");
I use a while loop to present data.
while($row = mysql_fetch_array($query5)) {}
I need one mysql query instead two.
If these tables are related you can JOIN them using the foreign key.
If I'm not mistaken this pId in the table pages_admin is a foreign key to the id on the table pages, is that correct?
If so, you could do something like this to you query:
"SELECT * FROM pages p
LEFT JOIN admin_pages ap on p.id = ap.pId
WHERE (`pId`=$switch AND `rand`=$randID AND `admin`!='{$_SESSION['user']}')"
Note that I've changed the syntax, instead of merging string you can use only one containing all variables you need.

Joining two Mysql Queries with php

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 ...

How to select value from a drop-down list, get the corresponding values from another table, then put those into another drop-down list?

Ok, here's a database.
http://i.stack.imgur.com/j05AB.png
Say I've inserted values into the database for each of these tables, although the IDs would be auto incrementing. There are many BVALUES from each AVALUE, thus the AB table. I have all the AVALUEs from TABLE A in a drop-down list. A user selects an AVALUE which I put into a variable using
$AVALUE = $_POST['AVALUE']
Then I do an sql statement to get the AVALUEs from TABLE A that equal $AVALUE.
$sql = "SELECT AVALUE FROM TABLEA WHERE" . $AVALUE . " = AVALUE";
How do I then get the NAMEID from TABLEA for that AVALUE, then reference to AB where TABLEANAMEID = NAMEID from TABLEA? Then I want to get all the BVALUES by getting all the TABLEBNAMEIDs that correspond to the TABLEANAMEIDs.
I then want those BVALUES in a drop-down list on a seperate HTML page. After a bit of Googling the solution I think would be to do some sort of a loop putting the BVALUES into a variable as all the NAMEIDs from TABLE B increment where the variable would be in an $BVALUE loop and the list values would show with all the BVALUES.
I hope I explained that right. I think I know what I'm trying to do but I have no idea how to actually implement it. Please help guys.
You need to join those table together. What you are describing is an m:n relation. In this case you have do use 2 joins like this:
SELECT * FROM TableA AS a WHERE a.avalue = $AVALUE
JOIN TableAB AS a2b ON a.namevalue = a2b.id_a
JOIN TableB AS b ON a2b.id_b = b.id
Maybe u means, u want to get all BVALUE which has relation with selected AVALUE in table AB
$sql = "SELECT B.NAMEID as id, BVALUE as value FROM TABLEA A
LEFT JOIN AB ON TABLEANAMEID=A.NAMEID
LEFT JOIN TABLEB B ON TABLEBNAMEID=B.NAMEID
WHERE AVALUE = $AVALUE";`
get mysql result
$result = mysql_query($sql);
iterate
echo "<select>";
foreach ($r = mysql_fetch_object($result)) {
echo '<option value="'.$r->id.'">'.$r->value.'</option>';
}
echo "</select>";

how to extract mysql data into json using php

i have retrieved mysql data from one table in json using the following script
$table_first = 'abc';
$query = "SELECT * FROM $table_first";
$resouter = mysql_query($query, $conn);
$set = array();
$total_records = mysql_numrows($resouter);
if($total_records >= 1){
while ($link = mysql_fetch_array($resouter, MYSQL_ASSOC)){
$set[] = $link;
}
}
echo json_encode($set);
how can i retrieved data from two other tables in which there is a foreign key of this table in both of those tables. OR simply how can i retrieved data from 3 mysql tables in php.
I believe the best way to go here is using a JOIN or just something like this:
$sql = "SELECT
tabl1.*, table2.*, tabl3.* FROM table1, table2, table3
WHERE
table1.fk1 = table2.id AND
table1.fk2 = table2.id";
//Do the whole selection process...
If you make the queries separately, you'll be forcing 3 queries onto your database and will end in a performance hit that you dont need. So, the idea is load all the data from the DB using joins or similar that and then encode the results. Is faster and you'll leave the merging work to MySQL
Hope I can help
You can get all data firstly.
Then merge the data array.
Finally use json_encode to change the data format.
There is a foreign key of this table in both so you can use "join" to retrieve values from other tables.
Suppose that there are two tables as State(st_id,st_name) and City(ct_id,ct_name,state_id). Now, primary key are st_id & ct_id respectively of tables State & City.
Connection between this two table can be establish by joining State.st_id and City.state_id.
Now, coming to your problem to retrieve data from two table State & City, we can make sql query like following,
$sql="select s.*, c.* from State s, City c
where s.st_id=c.state_id ";
Using above query you can fetch data from database and convert into json format and can send it to android system. here is a good article http://blog.sptechnolab.com/2011/02/10/android/android-connecting-to-mysql-using-php/. i hope you like it.
I believe your code roughly will look like this:
$query = "SELECT
A.column1 AS First_1
A.column2 AS First_2
B.column2 AS Second
C.column3 AS Third
FROM table1 A, table2 B, table3 C
WHERE
A.fk1 = B.id AND
B.fk2 = C.id";
where a column is a relevant record you want to show. Meanwhile,
AS will act as a key name in JSON.

Multiple left joins, how to output in php

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.

Categories