私はこのような「連絡先」テーブルを持っています。このようなPHPでは、対応する列を別のテーブルにどのようにして取得できますか?
contact_auto_inc user_id contact_id
1 1 3
2 1 5
3 2 1
4 3 5
5 3 2
6 1 6
と「ユーザー」テーブル:私が欲しいもの
user_id username
1 Simon
2 Bill
3 Tim
4 Brendan
5 Chris
6 Noel
がcontact_ids
のマッチングusernames
を印刷することです。
だからuser_id
1のために、例えば、私が印刷したい:
Tim
Chris
Noel
私はこれを行うことができますどのように?これは、印刷し
$user_id = $_SESSION['user_id'];
//we want to show contact_ids in the contacts table that have the $user_id above.
$select_from_contacts_table = "SELECT * FROM contacts WHERE user_id = '$user_id'";
//get the result of the above
$result=mysqli_query($con,$select_from_contacts_table);
while($row = mysqli_fetch_assoc($result)) {
$contact_id=$row['contact_id'];
echo $contact_id . "<br>";
}
:
私はと大丈夫contacts
テーブルからcontact_ids
を印刷することができ
3
5
6
をしかし、私は、私はuser
テーブル内の対応するusername
列を印刷することができますか?私はINNER JOIN
と時間しようとしているが、、エラーや間違った結果を得るための線に沿って何か維持されています:任意の助け
$select_from_user_table = "SELECT DISTINCT contact_id, username
FROM contacts
INNER JOIN user
ON contacts.contact_id=user.user_id WHERE user_id = '$user_id'";
//get the result of the above
$result2=mysqli_query($con,$select_from_user_table);
//show the usernames
while($row = mysqli_fetch_assoc($result2)) {
echo $row['username'] . "<br>";
}
感謝を。あなたは以下のようなwhileループでユーザ名を照会することができます
私はちょうどINNER JOINで正しいSQLを書いてあなたに投稿しましたが、それはDISTINCT以外のあなたのものとまったく同じであることに気付きました。違いはありません。奇妙なことに失敗します。 – smozgur
ああ! user_id =最後の部分。 contacts.user_idとされています。 – smozgur