PHP関数を使うのはかなり新しいですが、これまで私のコードは大部分のファイル(queries.php)に複数のクエリを保持していて、私のメインページはforeach
ループを使用しています。PHPの新機能とforeachループでの使用方法
ここでは、処理するダイナミックデータがたくさんある小さなネットワークサイトを構築しています。
私は関数はこの種のプロジェクトのために移動するための方法であることを聞いたと私は成功していない関数呼び出しに各ループのための機能と私に私のクエリの一部を変換しようとしているが - しばしば受けます解析エラー。
私は、例を示して自分のニーズに適応させることでかなりうまくやっていますが、私がネット上で見つけたチュートリアルでは苦労しています。私は、誰かが私を見せてそこから行くことができるという希望でいくつかのサンプルコードを含んでいます。
私は、現在のクエリを関数に変換して、foreach
ループを使用する代わりに関数を呼び出す方法や、同じクエリを複数回呼び出す必要があると考えていますか?
関数の例。
function getProfileGridsWithLocations(){
// BEGIN QUERY TO DISPLAY MEMBERS WITH LOCATION ON HOMEPAGE
$query = "SELECT
users.id AS id,
users.username AS username,
users.email as email,
users.created,
profilephotos.profilephoto_file AS photo,
profiles.profile_displayname AS displayname,
profiles.profile_displayage AS displayage,
locations.user_id,
locations.location_city,
frmlocations.location_id,
frmlocations.city AS City
FROM users
JOIN profilephotos ON users.id = profilephotos.user_id
JOIN profiles ON users.id = profiles.user_id
JOIN locations ON users.id = locations.user_id
JOIN frmlocations ON locations.location_city = frmlocations.location_id
WHERE locations.location_city = '$location' OR '$location' = ''
ORDER BY users.created DESC
/*LIMIT 20*/
";
try
{
$stmt = $db->prepare($query);
$stmt->execute();
}
catch(PDOException $ex)
{
die("Failed to run query: " . $ex->getMessage());
}
$members_with_locations_homepage = $stmt->fetchAll();
}
私のforeachループの例。
<div id="profiles" class="pages">
<div class="mem-grid-wrap">
<?php foreach($this->getProfileGridsWithLocations as $members_with_location_homepage): ?>
<div class="box">
<div class="boxInner" style="background-color:#000000;">
<a href="girl.php?username=<?php echo htmlentities($members_with_location_homepage['username'], ENT_QUOTES, 'UTF-8'); ?>&uid=<?php echo htmlentities($members_with_location_homepage['id'], ENT_QUOTES, 'UTF-8'); ?>">
<?php
echo (!empty($members_with_location_homepage['photo'])) ? "<img src='uploads/profile-photos/" . $members_with_location_homepage['photo']. "' />" : "<img src='assets/img/image-not-available.jpg' />";
?>
<div class="titleBox" style="text-align:left; line-height:20px;">
<span style="font-size:18px; font-weight:bold;"><i class="fa fa-female"></i> <?php echo htmlentities($members_with_location_homepage['displayname'], ENT_QUOTES, 'UTF-8'); ?>, <?php echo htmlentities($members_with_location_homepage['displayage'], ENT_QUOTES, 'UTF-8'); ?></span>
<br />
<span style="font-size:11px;"><i class="fa fa-map-marker"></i> <?php echo htmlentities($members_with_location_homepage['City'], ENT_QUOTES, 'UTF-8'); ?> | <i class="fa fa-clock-o"></i> Now</span>
</div>
</a>
</div>
</div>
<?php endforeach; ?>
</div>
</div>
私は機能では、上記のことを使用しているように私が現在使用していたクエリが含まれていませんでした。
質問は何ですか。 – Epodax