我想在另一個數組的foreach語句中使用一個數組中的變量。從一個foreach語句中檢索變量並在另一個foreach語句中顯示
我有一個網格視圖,顯示用戶的個人資料照片,他們的顯示名稱,當前位置和可用性,以及使用他們的用戶名來完成應用於該框的鏈接。
用戶表保存;用戶名(和用戶ID)應該在將來需要。
配置文件表保存;顯示名稱。
profilephotos表保存;個人資料照片。
位置表保存;當前位置。
所有通過與用戶表匹配的user_id和username列都鏈接到表中。
我對用戶框的代碼是;
<?php foreach($rows as $row): ?>
<div class="box">
<div class="boxInner">
<a href="profile.php?username=<?php echo htmlentities($row['username'], ENT_QUOTES, 'UTF-8'); ?>&uid=<?php echo htmlentities($row['id'], ENT_QUOTES, 'UTF-8'); ?>">
<img src="uploads/profile-photos/<?php echo htmlentities($pphoto['profilephoto_file'], ENT_QUOTES, 'UTF-8'); ?>" />
<div class="titleBox" style="text-align:left; line-height:20px;">
<span style="font-size:18px; font-weight:bold;"><i class="fa fa-user"></i> <?php echo htmlentities($row['profile_displayname'], ENT_QUOTES, 'UTF-8'); ?>,
<?php echo htmlentities($row['profile_displayage'], ENT_QUOTES, 'UTF-8'); ?></span>
<br />
<span style="font-size:14px;"><i class="fa fa-map-marker"></i> City Name | <i class="fa fa-clock-o"></i> Now</span>
</div></a>
</div>
</div>
<?php endforeach; ?>
我的SQL查詢和數組代碼是;
$query = "
SELECT
users.id,
users.username,
users.email,
profiles.profile_displayname,
profiles.profile_displayage,
profiles.profile_photo
FROM users, profiles
WHERE users.id = profiles.user_id;
";
try
{
// These two statements run the query against your database table.
$stmt = $db->prepare($query);
$stmt->execute();
}
catch(PDOException $ex)
{
// Note: On a production website, you should not output $ex->getMessage().
// It may provide an attacker with helpful information about your code.
die("Failed to run query: " . $ex->getMessage());
}
// Finally, we can retrieve all of the found rows into an array using fetchAll
$rows = $stmt->fetchAll();
$query = "
SELECT
users.id,
users.username,
profilephotos.user_id,
profilephotos.profilephoto_file
FROM users, profilephotos
WHERE users.id = profilephotos.user_id;
";
try
{
// These two statements run the query against your database table.
$stmt = $db->prepare($query);
$stmt->execute();
}
catch(PDOException $ex)
{
// Note: On a production website, you should not output $ex->getMessage().
// It may provide an attacker with helpful information about your code.
die("Failed to run query: " . $ex->getMessage());
}
// Finally, we can retrieve all of the found rows into an array using fetchAll
$profilephotos = $stmt->fetchAll(PDO::FETCH_ASSOC);
無論我嘗試什麼 - 我只是不能讓foreach拉入正確的圖像。我設法拉入一張圖片,但foreach語句對每個用戶都應用相同的圖片,而不管我指示查詢$profilephotos
的查詢的ID。
我在做什麼錯?我甚至會以正確的方式去做這件事嗎?
任何幫助將不勝感激 - 請注意,雖然我是PHP新手。
感謝 - 似乎已經解決了它 - 只是一個問題,如果用戶更改了他們的配置文件映像,我將如何更改該查詢以獲取每個user_id(理想狀態下最新)的結果?我有兩個框出現,因爲對於同一個用戶,在單獨的行中有兩個圖像。 –
一切都是可能的,但我認爲它是你的數據庫結構有問題(我更接近查詢)。請描述你的表格的用途。可能是更改表格模式更好。 –