Get data from 3 table with Inner Join MySQL php - php

include '../incs/connect.php';
$q=mysqli_query($con,"SELECT appl_reg_details.appl_id, appl_reg_details.apl_name, appl_reg_details.apl_email, rp_test_result.appl_status, rp_intv_result.intv_obt_marks
FROM appl_reg_details
INNER JOIN rp_test_result ON appl_reg_details.appl_id = rp_test_result.appl_id
INNER JOIN rp_intv_result ON rp_test_result.appl_id = rp_intv_result.appl_id
GROUP BY appl_reg_details.appl_id
");
WHILE($row=mysqli_fetch_array($q))
{
echo $row=['appl_id']." - ";
echo $row=['apl_name']." - ";
echo $row=['intv_obt_marks']." - ";
echo $row=['appl_status']." -";
echo $row=['apl_email']."<br/>";
}
I have 3 tables and i want to get data of 3 field from table1, of 1 field from table 2 and table 3 each, i have found that inner join can do this, when i run this it says 'Notice: Array to string conversion',
help to correct this or give a new way please

The query looks fine at first glance.
The problem is with the lines below it. They include an unnecessary =:
echo $row=['apl_email']."<br/>";
These lines should be like this:
echo $row['apl_email']."<br/>";

Performance benefits aside, GROUP BY serves no purpose here other than to confuse the result set. Try something like this instead, and fix the coding errors identified by rjdown:
SELECT DISTINCT d.appl_id
, d.apl_name
, d.apl_email
, t.appl_status
, i.intv_obt_marks
FROM appl_reg_details d
JOIN rp_test_result t
ON t.appl_id = d.appl_id
JOIN rp_intv_result i
ON r.appl_id = i.appl_id;

Related

How to adjust this query of research?

I need to adjust this query to do the search (like) in another column and another table.
See:
$query2 = "
select distinct(lances.codigo)
, datacompra
, horacompra
, cupom
from lances
, ".$tabelaCad."
where lances.idcliente = ".$tabelaCad.".id
and lances.datapgto = '0000-00-00'
and lances.horapgto = '00:00:00'
and (".$tabelaCad.".nome like '%".$cliente."%' or ".$tabelaCad.".usuario like '%".$cliente."%')
group
by lances.codigo
order
by lances.datacompra desc
, lances.horacompra desc
";
He currently searches only on: ".$tabelaCad.".nome and ".$tabelaCad.".usuario.
The variable $tabelaCad is the name of a table called cadastro, and the variable cliente is the one that receives the search POST.
I need her to look too in the column codigo from the table lances and in a new table called registro in the columns reg1 e reg2.
What would the query look like in this case? I have tried several ways and it does not work.
I am working with MySQL 5.7, still...
After a long discussion we found the last relation between the tables.
It is registro.reg1 to lances.codigo.
So the best way to solve the problem is to work with the inncer join.
You save unnecessary typing and can address the tables with aliases which is much more comfortable for writing procedures.
Here is my finished solution:
<?php
$query2 = "
select
distinct lc.codigo as codigo,
lc.datacompra as datacompra,
lc.horacompra as horacompra,
lc.cupom as cupom
from `lances` as lc
inner join `".$tabelaCad."` as ca on lc.idcliente = ca.id
inner join `registr` as ri on lc.codigo = ri.reg1
where lc.idcliente = ca.id
and lc.datapgto = '0000-00-00'
and lc.horapgto = '00:00:00'
and (ca.nome like '%".$cliente."%' or ca.usuario like '%".$cliente."%')
group
by lc.codigo
order
by lc.datacompra desc, lc.horacompra desc
";
?>
I put them in the selection because I do not know exactly what you intend to xD

PHP, MYSQL: Select inside a while Loop?

I am requesting your advice about the following:
I have two tables:
Customers and Orders.
I am printing the data of customers inside a table using a while loop:
$sql = "SELECT * FROM wccrm_customers where status = '1' order by date desc";
$result = mysql_query($sql, $db);
while ($daten = mysql_fetch_array($result)) { ?>
echo $daten[id];
echo $daten[name] . ' ' . $daten[vorname];
echo $daten[email];
echo $daten[telefon];
} ?>
Now I try to add a new field in this list: Purchased YES/NO. As we have more customers then buyers, we want to show whether someone has bought or not:
The Connection between this two tables is the first/lastname in both tables!
So if customer.name = orders.name and customer.firstname = orders.firstname I want to echo "YES" if not then "NO"
I tried with a JOIN, but here I just get the results who are in both table:
SELECT *
FROM wccrm_customers AS k
INNER JOIN wccrm_orders AS o
ON o.namee = k.name AND o.firstname = k.firstname
but I need to have all of the customers and the ones who are in both lists marked...
Is this possible? If yes: How can I achieve this?
Thank's for your advice!
Kind regards,
Stefan
This has nothing to do with PHP, or with while loops; you just need to form your join properly:
SELECT DISTINCT
`k`.*,
`o`.`namee` IS NOT NULL AS `Purchased`
FROM `wccrm_customers` AS `k`
LEFT JOIN `wccrm_orders` AS `o`
ON
`o`.`namee` = `k`.`name`
AND `o`.`firstname` = `k`.`firstname`
Read more about the different join types: http://www.sql-join.com/sql-join-types/
(images courtesy of that site, which also contains an example and discussion of almost exactly what you're trying to do!)
By the way, you must have missed the massive red warning banner in the manual about using the deprecated (now removed) mysql_* functions. You should stop doing that! Use MySQLi or PDO instead.
a shorter one
SELECT DISTINCT k.*, IF(o.namee IS NULL, 'no', 'yes') purchased
FROM
wccrm_customers AS k
LEFT JOIN wccrm_orders AS o USING (namee,firstname)

Return all rows from table one even if table two is empty or partial results found

I am trying to return all the results from table one, AKA ship_skill_tree, while matching up the rows found in table two, AKA character_sheet_skills, even if the rows do not exist in table two.
SELECT c.`level` , t.`skillLevel` AS levelNeeded, i.`typeName`
FROM `ship_skill_tree` t
LEFT JOIN `character_sheet_skills` c ON t.`skillTypeID` = c.`typeID`
LEFT JOIN `invTypes` i ON i.`typeID` = t.`skillTypeID`
WHERE t.`shipTypeID` = 11176 AND c.`character_id` = 1;
Table One Data:
|shipTypeID|shipGroupID|skillTypeID|skillLevel
______________________________________________
|11011|26|3332|1
|11129|31|3327|1
|11132|31|3327|1
|11134|31|3327|1
|11172|830|3328|5
|11172|830|12093|1
|11174|893|3328|5
|11174|893|28615|1
|11176|831|3330|5
|11176|831|12092|1
Table Two Data:
|character_id|typeID|skillpoints|level|published
______________________________________________
|1|3300|1415|2|1
|1|3301|8000|3|1
|1|3327|256000|5|1
|1|3330|2829|2|1
|1|3340|181020|4|1
|1|3341|1024000|5|1
|1|3342|32000|3|1
|1|3343|32202|3|1
|1|3380|256000|5|1
|1|3385|256000|5|1
|1|3386|256000|5|1
|1|3392|256000|5|1
|1|3394|90514|4|1
|1|3402|256000|5|1
|1|3410|768000|5|1
|1|3411|135765|4|1
|1|3412|750|1|1
|1|3413|256000|5|1
|1|3416|45255|4|1
|1|3417|0|0|1
|1|3418|0|0|1
|1|3419|135765|4|1
|1|3420|181020|4|1
|1|3423|0|0|1
|1|3425|90510|4|1
|1|3426|45255|4|1
|1|3428|500|1|1
|1|3429|8000|3|1
|1|3436|45255|4|1
|1|3437|45255|4|1
|1|3438|500|1|1
|1|3449|256000|5|1
|1|3453|0|0|1
|1|3455|256000|5|1
|1|3456|226275|4|1
|1|11579|271530|4|1
|1|12186|0|0|1
|1|12187|0|0|1
|1|12188|0|0|1
|1|12190|22547|3|1
|1|12191|45255|4|1
|1|12192|45255|4|1
|1|12193|45255|4|1
|1|12195|45255|4|1
|1|16281|256000|5|1
|1|17940|1024000|5|1
|1|20342|1280000|5|1
|1|22551|40000|3|1
|1|22578|181020|4|1
|1|25739|0|0|1
|1|26252|16000|3|1
|1|26253|750|1|1
|1|26261|750|1|1
|1|32918|16000|3|1
invTypes table:
|typeID|typeName
________________
|3327|Spaceship Command
|3328|Gallente Frigate
|3330|Caldari Frigate
|3332|Gallente Cruiser
|12092|Interceptors
|12093|Covert Ops
|28615|Electronic Attack Ships
In the above query shipTypeID will always, or should always, be valid and match a record in table one, however, in table two, the rows that match may not exist. What I need is to output as follows:
|level|levelNeeded|typeName
___________________________
|2|5|Caldari Frigate
|NULL|1|Interceptors
Currently this is what is returned:
|level|levelNeeded|typeName
___________________________
|2|5|Caldari Frigate
EDIT: Solution!
SELECT c.`level` , t.`skillLevel` AS levelNeeded, i.`typeName`
FROM `ship_skill_tree` t
LEFT JOIN `character_sheet_skills` c ON t.`skillTypeID` = c.`typeID` AND c.`character_id` = 1
INNER JOIN `invTypes` i ON i.`typeID` = t.`skillTypeID`
WHERE t.`shipTypeID` = 11176
You need to put any restrictions on the table being joined in the ON clause. If you put them in the WHERE clause it doesn't work, because the rows that don't have any matches will produce NULL for those columns, and the WHERE clause will filter them out.
SELECT c.`level` , t.`skillLevel` AS levelNeeded, i.`typeName`
FROM `ship_skill_tree` t
LEFT JOIN `character_sheet_skills` c ON t.`skillTypeID` = c.`typeID` AND c.`character_id` = 1
LEFT JOIN `invTypes` i ON i.`typeID` = t.`skillTypeID`
WHERE t.`shipTypeID` = 11176
DEMO
You need to use a right join or an outer join rather than a left join. Have a look through the Visual Representation of SQL Joins for a good overview

PHP: Left Join 2 table and print all records

I have two table records in my database which look like this:
Table 1 with the column 1:
topic_id name
21 my computer
table 2 with columns as follows:
reply_id topic_id message
1 21 blabla
2 21 blue
In which the topic_id column in the table 2 is the foreign key of the table 1
I wanted to echo all replies in the table 2 along with the topic name (#21) in the table 1. So, I made the query like this
$q="SELECT name, message
FROM table1
LEFT JOIN table2
ON table1.topic_id = table2.topic_id
";
However, the result/ output returns the topic's name and ONLY ONE reply, but not 2 (or all) as expected. Did I miss something?
I used LEFT JOIN because some topics are still waiting for replies. In case that there is not any reply, the topic's name is still printed in browsers.
I also tried adding
GROUP BY table1.topic_id
but still NO LUCK!
Can you help? Thanks
EDIT: To clarify the question I add the php code to fetch records as follows:
As you know, The name needs to be printed only once. So, I code like this:
$tid = FALSE;
if(isset($_GET['qid']) && filter_var($_GET['qid'], FILTER_VALIDATE_INT, array('min_range'=>1) ) ){
// create the shorthand of the question ID:
$tid = $_GET['tid'];
// run query ($q) as shown above
$r = mysqli_query($dbc, $q) or die("MySQL error: " . mysqli_error($dbc) . "<hr>\nQuery: $q");
if (!(mysqli_num_rows($r) > 0) ){
$tid = FALSE; // valid topic id
}
}//isset($_GET['qid']
if ($tid) { //OK
$printtopic = FALSE; // flag variable to print topic once
while($content = mysqli_fetch_array($r, MYSQLI_ASSOC)){
if (!$printtopic) {
echo $content['name'];
$printtopic= TRUE;
}
}
} // end of $tid
// Print the messages if any:
echo $content['message'];
Try this with inner join
$q="SELECT name, message
FROM table1
INNER JOIN table2
ON table1.topic_id = table2.topic_id";
Try:
$q="SELECT table2.reply_id, table1.name, table2.message
FROM table2
LEFT JOIN table1
ON table1.topic_id = table2.topic_id
";
After struggling with this issue, I can find out that the problem is that I had to change the query to INNER JOIN and add the WHERE clause like this:
WHERE table2.reply_id = {the given topic_id}
Then it works well!
Sorry to disturb you all!

How to LEFT JOIN on when columns have the same name

The title is a bit confusing, hopefully it is clear what I am trying to do from my query. I thought I understood joins, clearly not, here is my $query:
SELECT DATE(T0.timestamp),
SUM(T0.total_responses),
SUM(T0.responses),
T0.metric_id,
T1.metric_id
FROM `personal_aggregates` AS T0
LEFT JOIN `qrs_metrics` AS T1
ON T0.metric_id = T1.qrs_metric_id
WHERE T0.user_id = 1 AND
T0.duration = '1' AND
T0.category_id IN (1,2,3,4) AND
T0.timestamp >= 'period_duration'
GROUP BY DATE(T0.timestamp)";
I am trying to join the tables on the columns metric_id and qrs_metric_id. However I get no results from the above query. When I loop through the result in PHP and check any of the variables, for example $result['T0.metric_id'], I get Undefined index: T0.metric_id
If anyone can shed any light on this I would much appreciate it.
Try this:
$query = "SELECT DATE(T0.timestamp), SUM(T0.total_responses), SUM(T0.responses),
T0.metric_id AS metric0, T1.metric_id AS metric1
FROM `personal_aggregates` AS T0
LEFT JOIN `qrs_metrics` AS T1 ON T0.metric_id = T1.qrs_metric_id
WHERE T0.user_id = 1 AND T0.duration = '1'
AND T0.category_id IN (1,2,3,4)
AND T0.timestamp >= 'period_duration'
GROUP BY DATE(T0.timestamp)";
you can now make a difference by using this:
echo $row['metric0'];
echo $row['metric1'];
Either you need to add some aliases to your selected columns
SELECT DATE(T0.timestamp) as tstamp, SUM(T0.total_responses) as responses...
and refer to the columns by alias:
$result['tstamp']
or you can refer to the columns by numeric index:
$result[0]
Your query should be
$query = "SELECT
DATE(T0.timestamp) AS T0timestamp,
SUM(T0.total_responses) AS total_responses,
SUM(T0.responses) AS responses,
T0.metric_id,
T1.metric_id AS metric_id_2
FROM `personal_aggregates` AS T0
And accessed like
$result['metric_id'];
$result['metric_id_2'];
$result['T0timestamp'];
$result['total_responses'];
Exclude the table alias from the associative array access e.g. "T0.XXX" is wrong. You can only do that in the SQL

Categories