Legatura 2 tabele si afisare

Buna ziua am si eu o problema.
As dori sa leg cele 2 tabele iar apoi sa afisez informatii din cele 2 tabele, diferit. Mai exact:

tabelul 1 care se cheama gamehistory

teamid | matches | kills | damage | rating

tabelul 2 care se cheama teams

id | teamid | teamname | imgpath | created_at

Nu imi dau seama cum as putea lega cele 2 tabele astfel sa afisez kill-urile sau damage-ul din tabela 1 pentru echipa din tabela 2.

Mysql-ul arata asa:

$queryTeams = "
SELECT
    pbt.*

FROM
    pbmr_teams as pbt
";

$stmtQueryTeams = mysqli_stmt_init($connection);

if(!mysqli_stmt_prepare($stmtQueryTeams, $queryTeams)){
    echo 'Statement failed';
} else {
    mysqli_stmt_execute($stmtQueryTeams);
    $resultQueryTeams = mysqli_stmt_get_result($stmtQueryTeams); 
}

$teamsAssoc = mysqli_fetch_array($resultQueryTeams);
$teamsId =  $teamsAssoc['id']; 

$queryGameh = "
SELECT
    pbh.*
FROM
    pbmr_gamehistory as pbh,
    pbmr_teams as pbt  
WHERE
    pbh.teamid = pbt.teamid AND
    pbt.teamid = '.$teamsId.'     
";

$stmtGameh = mysqli_stmt_init($connection);

if(!mysqli_stmt_prepare($stmtGameh, $queryGameh)){
    echo 'Statement failed';
} else {
    mysqli_stmt_execute($stmtGameh);
    $resultGameh = mysqli_stmt_get_result($stmtGameh); 
}

As dori sa le afisez aici.

Exemplu inainte de numele echipei sa iau imgpath din tabela 2 si datele corespunzatoare tabelei 1.
Multumesc!

Poti face join intre tabele. Cele doua tabele le legi prin teamid.

In cazul tau o sa ai

select gh.kills, gh.damage
from gamehistory gh
join teams t on gh.teamid = t.teamid

gh si t sunt alias-uri pt cele 2 tabele

Si acum daca vreau sa le afisez?

Ar fi ok asa?

while($teamsRow = mysqli_fetch_array($resultGameh)){
      $teamid = $teamsRow['teamid'];

Da
Query-ul de mai sus iti returneaza un tabel si il afisezi cum faci de obicei.

Il poti executa si in phpmyadmin.

Functioneaza dar doar pentru tabelul gamehistory

Daca incerc sa afisez numele echipei $teamName = $teamsRow['team']; din tabelul teams imi returneaza
Notice: Undefined index: team

team nu exista in lista de coloane returnata de query-ul cu join. Trebuie sa adaugi si coloana team. Poti folosi un alias si pt coloane. column_name as ce_alias_vrei_tu Ar trebui sa mearga asa.

$teamName este un array asociativ si ai nevoie de cheie pt a afla valoarea.


http://php.net/manual/ro/mysqli-result.fetch-array.php

Multumesc frumos am rezolvat. Asta mi-a rezolvat multe probleme anterioare.
Raman dator :blush:

2 Likes