Display result if Table names are the same due to INNER JOIN - php

I don't know how to Explain my problem so here it goes
I have a Table called asalink with codes linked to names in a table called asatbl
I'm joining the tables but need the same Field to Display twice due to a different key
Please see my code Maybe this explains it better
$sele = "SELECT asatbl_1.asaName, asatbl_1.asaSurname, asatbl.asaName, asatbl.asaSurname, asalink.linkammount
FROM asatbl AS asatbl_1 INNER JOIN (asalink INNER JOIN asatbl ON asalink.asaid = asatbl.asaid) ON asatbl_1.asaSales_ref = asalink.asaSales_ref
WHERE asalink.asaSales_ref=1001";
$result = mysql_query($sele);
echo "<table border='1' cellpadding='10'>";
echo "<tr> <th>ASA Name</th> <th>ASA Surname</th> <th>Recipient Name</th> <th>Recipient Surname</th> <th>Amount</th></tr>";
if($mak = mysql_num_rows($result) > 0){
while($row = mysql_fetch_assoc($result)){
echo "<tr>";
echo '<td>' . $row['asaName'] . '</td>';
echo '<td>' . $row['asaSurname'] . '</td>';
echo '<td>' . $row['asatbl_1.asaName'] . '</td>';
echo '<td>' . $row['asatbl_1.asaSurname'] . '</td>';
echo '<td>' . $row['li nkammount'] . '</td>';
echo '<td>Edit</td>';
//echo '<td>Delete</td>';
echo "</tr>";
as you can see I used asatbl_.asaName and asatbl_1.Surname but does not work
Thanks in advance for help
Regards

Use an alias for the field names in result:
SELECT asatbl_1.asaName as fld1, asatbl_1.asaSurname as fld2, ... and so on.
Then to retrieve data reference the alias in resultset
$row['fld1']
$row['fld2']
...
Hopes this helps

I see a problem with the way you are trying to get the values of the fields using $row['asatbl_1.asaName'] and $row['asatbl_1.asaSurname']. You have to simply use $row['asaName'] and $row['asaSurname'] by removing table names before the column names.
After running any SQL query in PHP which has columns fetched along with table name using .(dot) through notations like - SELECT **table_name.column_name** FROM table_name you should not access the column values in the PHP query result with the table name prefixed to it which you are doing in $row['asatbl_1.asaName'] and $row['asatbl_1.asaSurname'].

Related

PHP MYSQL SELECT AND LEFT JOIN - not returning all results

I have two tables customer and customer_transaction. Both have common customer_id, but customer_transaction also has a field description that I want to return with my result, based on the common customer_id.
The result works correctly, but omits the customer_id for all records that don't have both customer_id and customer_transaction. description as per image. I am sure that I am missing something small here.
A portion of the relevant code. I seem to think the problem lies in the SELECT statement.
$sql = "SELECT * FROM customer LEFT OUTER JOIN customer_transaction ON customer. customer_id =customer_transaction. customer_id WHERE customer.customer_group_id = $input";
$sth = $pdo->prepare($sql);
$sth->bindParam(':start',$start,PDO::PARAM_INT);
$sth->bindParam(':length',$length,PDO::PARAM_INT);
$sth->bindParam(':query',$query,PDO::PARAM_STR);
$sth->execute();
foreach ($sth->fetchAll(PDO::FETCH_ASSOC) as $row) {
$phpvar = "$row[description] "; //creat variable for descriptio so as to limit the length using substr
echo '<tr>';
echo '<td>'. $row['customer_id'] . '</td>';
echo '<td>'. $row['company_name'] . '</td>';
echo '<td>'. $row['firstname'] ." ". $row['lastname'] .'</td>';
echo '<td>'. $row['email'] . '</td>';
echo '<td>'. $row['telephone'] . '</td>';
echo '<td>'. $row['customer_id'] . '</td>';
echo '<td>'. $row['customer_group_id'] . '</td>';
echo '<td>'. substr($phpvar,0) . '</td>'; //Limit the length of the transactions here
echo '<td width=250>';
The problem is that you have customer_id twice. The array however can have only one key with the name customer_id. The values are simply copied to the array field by field, using the field name as key. The value of the second occurrence, the one from the customer_transaction table, is overwriting the one from the customer table, and because not every customer has a transaction, you'll get empty fields there.
The best solution is to be more exact in the fields you need. It is good practise anyway to only fetch the fields you need instead of using *.
As a result, your query could look like this. A little more verbose, but with the flexibility of using aliases, calculated values and without the overhead of returning fields that you don't use.
SELECT
c.customer_id,
c.company_name,
c.firstname,
c.email,
c.telephone,
/* You could provide the field with an alias */
t.customer_id as transaction_customer_id,
/* Or use its value to return a more sensible value */
CASE WHEN t.customer_id IS NULL
THEN 'N'
ELSE 'Y' END AS has_transaction,
t.customer_group_id
FROM customer
LEFT OUTER JOIN customer_transaction ON customer. customer_id = customer_transaction.customer_id
WHERE customer.customer_group_id = $input

Display column from SQL query with same name

how can I display the name of both teams (lteam and vteam)? Query works now... This is a screenshot of the SQL results:
http://prntscr.com/f9mkqh
$sql = "
SELECT *
FROM fixtures
LEFT
JOIN teams AS a
ON fixtures.lteam = a.id
LEFT
JOIN teams AS b
ON fixtures.vteam = b.id
WHERE date_ko = '2017-05-19'
";
echo '<table>';
echo '<tbody>';
foreach($pdo->query($sql) as $row)
{
echo '<tr>';
echo '<td>' . $row['lteam'] . '</td>';
echo '<td>' . $row['name'] . '</td>';
echo '<td>-</td>';
echo '<td>' . $row['vteam'] . '</td>';
echo '<td>' . $row['b.name'] . '</td>';
echo '</tr>';
}
echo '</tbody>';
echo '</table>';
Thanks!
The SQL result header is somewhat confusing, and as I don't know fully how the tables and schemas are structured, I have to assume you are having trouble with getting the name attribute from the teams table, as this is joined in two times.
You will need to select the columns explicitly and naming them something else for this to work. For example:
SELECT *, `a`.`name` as `team1name`, `b`.`name` as `team2name` FROM fixtures [...]
Now you should be able to grab the team names under their assigned aliases.

Displaying multiple tables depending on data available

I am trying to display data from multiple tables on one page but I need to do different queries to get all the people to show up. How do I format a query where it will select data from the job/jobSearch table if there is data that matches with the studentID from the student and major tables or select from the education table if there is data that matches the studentID. Both job/jobSearch and the education tables will not have data for the same student at the same time because they will either be choosing that they are employed after graduation or continuing their education so if they choose education they skip the questions regarding employment and vice versa.
<?php
include('includes/db_connect.php');
//include('student.php');
$query_student="SELECT *
FROM student
JOIN major
ON student.studentID=major.studentID
JOIN jobSearch
ON major.studentID=jobSearch.studentID
JOIN job
ON jobSearch.studentID=job.studentID
JOIN education
ON job.studentID=education.studentId";
$result_student=mysqli_query($conn, $query_student) or die(mysqli_error($conn));
echo '<table>
<tr>
<th>First Name</th>
<th>Last Name</th>
<th>Graduate Year</th>
<th>Major</th>
<th>Activity After Graduation</th>
</tr>';
while($row = mysqli_fetch_array($result_student))
{
echo'<tr>'; // printing table row
echo '<td>' . $row['firstName'] . '</td>';
echo '<td>' . $row['lastName'] . '</td>';
echo '<td>' . $row['gradDate'] . '</td>';
echo '<td>' . $row['major'] . '</td>';
echo '<td>' . $row['activity'] . '</td>';
echo'</tr>'; // closing table row
}
echo '</table>';
$conn->close();
?>

How to join two tables with multiple common fields for search filter

I have 2 table bpi_registration and bpi_teamProfile. The fields in bpi_registration are : id, id_school, first_name,last_name,email,city,state,country and fields in bpi_teamProfile table are id_team, team_name, id_student1, id_student2, id_student3 now id_student1, id_student2, id_student3 contains the same id of students that were in bpi_registration. I am not sure how to connect multiple fields. The query that i have written is below. Please correct me if i am wrong:
SELECT * FROM bpi_registration
INNER JOIN bpi_teamProfile
ON bpi_registration.id=bpi_teamProfile.id_student1
AND bpi_registration.id=bpi_teamProfile.id_student2
AND bpi_registration.id=bpi_teamProfile.id_student3
AND bpi_registration.id=bpi_teamProfile.id_student4
AND bpi_registration.id=bpi_teamProfile.id_student5
I am trying to implement search filter in such a way that when someone clicks on Team dropdown then the firstname,lastname,email,city,state,country from bpi_registrationshows up. Below is my PHP code
if (isset($_GET['Team']))
{
$sql="SELECT * FROM bpi_registration
INNER JOIN bpi_teamProfile
ON bpi_registration.id=bpi_teamProfile.id_student1
AND bpi_registration.id=bpi_teamProfile.id_student2
AND bpi_registration.id=bpi_teamProfile.id_student3
AND bpi_registration.id=bpi_teamProfile.id_student4
AND bpi_registration.id=bpi_teamProfile.id_student5"
$userQuery = "{$sql} WHERE bpi_teamProfile.team_name = :team_id";
$user = $db->prepare($userQuery);
$user->execute(['team_id' => $_GET['Team']]);
$selectedUser=$user->fetch(PDO::FETCH_ASSOC);
if(isset($selectedUser))
{
echo '<tr>';
echo '<td>' . $selectedUser['first_name'] . '</td>';
echo '<td>' . $selectedUser['last_name'] . '</td>';
echo '<td>' . $selectedUser['email'] . '</td>';
echo '<td>' . $selectedUser['address_city'] . '</td>';
echo '<td>' . $selectedUser['address_state'] . '</td>';
echo '<td>' . $selectedUser['address_country'] . '</td>';
echo '</tr>';
}
}
The URL looks when we click on team filter looks like this - https://www.example.com/retrieve1.php?Grade=&School=&Team=mary+winners&Students=
However i am not able to get the desired result.
It seems unlikely the student id columns in a given row all map back to the same id (in registration)...or the query would be returning properly. If they are different, do want to 'OR' the join?
SELECT * FROM bpi_registration
INNER JOIN bpi_teamProfile
ON (bpi_registration.id=bpi_teamProfile.id_student1)
OR (bpi_registration.id=bpi_teamProfile.id_student2)
OR (bpi_registration.id=bpi_teamProfile.id_student3)
OR (bpi_registration.id=bpi_teamProfile.id_student4)
OR (bpi_registration.id=bpi_teamProfile.id_student5)

Filter already output mysql data in HTML table

I have my MySQL data output into a HTML table successfully and exactly how I want it. Now I'd like to filter this data based on multiple dropdown values and a submit button. I've looked around in tutorials and other questions but can't find what I'm looking for. Here's how I output:
$fetchResult = "SELECT a.MembershipID, a.FirstName, a.Surname, t.RaceID, r.RaceName, t.Time, r.RaceID, r.ClubYear
FROM Athlete AS a
INNER JOIN Time AS t
ON a.MembershipID=t.MembershipID
INNER JOIN Race AS r
ON t.RaceID=r.RaceID
ORDER BY a.Surname";
$result = $mysqli->query($fetchResult);
//Start table
echo "<table>";
echo "<tr>
<th>First Name</th>
<th>Surname</th>
<th>Race</th>
<th>Time</th>
<th>Club Year</th>";
// Loop through database
while ($row = mysqli_fetch_array($result)) {
echo '<tr>';
echo '<td>' . $row['FirstName'] . '</td>';
echo '<td>' . $row['Surname'] . '</td>';
echo '<td>' . $row['RaceName'] . '</td>';
echo '<td>' . $row['Time'] . '</td>';
echo '<td>' . $row['ClubYear'] . '</td>';
}
echo "</tr></table>";
Now I have 4 dropdowns also populated by data from the database. What I'd like to happen is, the user picks an option between 1 and 4 dropdowns and the data in the HTML gets filtered but I can't get this to work. Here is what I have so far:
if (!empty($clubYear)) {
$fetchResult = "SELECT a.MembershipID, a.FirstName, a.Surname, t.RaceID, r.RaceName, t.Time, r.RaceID, r.ClubYear
FROM Athlete AS a
INNER JOIN Time AS t
ON a.MembershipID=t.MembershipID
INNER JOIN Race AS r
ON t.RaceID=r.RaceID
WHERE r.ClubYear='$clubYear'
ORDER BY a.Surname";
}
$result = $mysqli->query($fetchResult);
So I check to see if the dropdown is empty, if not, apply a query with a WHERE filter. This just makes the page refresh and go to a "no data received" page. Where am I going wrong? The filter should be applied based on what's been selected in the dropdown but without explicitly stating what that dropdown equals i.e= if $clubYear == "whatever", then WHERE r.ClubYear="whatever" - I'd like to just filter through passing the variable.
Thanks.

Categories