0

foreach 内で 2 つのクエリを実行する必要がありますが、エラーなしでは実行できません。

だから、私はコメントを表示するためにこれを持っています:

$query = 'SELECT * FROM comments WHERE updatepostid = "' . $postID . '"';
    try {
        $stmt = $db->prepare($query);
        $stmt->execute();
        $countcomments = $stmt->rowCount();
        }
        catch (PDOException $ex) 
        {
            die("Failed to run query: " . $ex->getMessage());
        }

$rows = $stmt->fetchAll();
foreach ($rows as $row):
$commentID       = $row['commentID'];
$usercommentID   = $row['userID'];
$commentusername = ucfirst($row['commentusername']);
$comment         = ucfirst($row['comment']);
$updatepostid    = $row['updatepostid'];

<div class="textcomment">
    <?php
        echo "<a class='$rightscommentcolor'>$commentusername:</a>&nbsp; $comment";
    ?>
</div>


<?php endforeach; ?>

ただし、ユーザーデータベースで別のクエリを実行して、ユーザーが持っている権限を確認し、コメントユーザー名のクラスをそのクラスに設定したいと考えています。

そのクエリは例えば

    <?php

$query2 = 'SELECT * FROM users WHERE id = "' . $usercommentID . '"';
    try {
        $stmt = $db->prepare($query2);
        $stmt->execute();
        }
        catch (PDOException $ex) 
        {
            die("Failed to run query: " . $ex->getMessage());
        }

$rows = $stmt->fetchAll();
foreach ($rows as $row):
$rights = $row['rights'];

if ($rights = '1') {
    $rightscommentcolor = 'userrights1';
} else if ($rights = '5') {
    $rightscommentcolor = 'userrights5';
}

?>
<?php endforeach; ?>

これについてどのように行くのが適切な方法ですか?

PS私は、上記のコードがおそらく人々を泣かせることを理解しています.

4

2 に答える 2

4

結合で単一のクエリを使用します。また、PDO を使用しているため、文字列を連結するのではなく、パラメーター化されたクエリを使用する必要があります。

$query = "SELECT * FROM comments c
          JOIN users u ON u.id = c.userID
          WHERE updatepostid = :updatepostid";
try {
    $stmt = $db->prepare($query);
    $stmt->execute(array(':updatepostid' => $postID));
    }
catch (PDOException $ex) 
    {
        die("Failed to run query: " . $ex->getMessage());
    }
于 2013-11-04T22:19:39.527 に答える