doukan6564 2019-06-21 05:14
浏览 104
已采纳

我的循环中的数据不匹配,不确定原因

I have a code that is suppose to display messages back and forth between the users. For some reason the data is mismatching and I'm not sure where in my code I have the error. I've tried to change my if statements of $x < $sender but that didn't work.

1

but the data being displayed doesn't line up with the database information.

2

"Test 2" message was sent from woof3, so it should be green and not blue when logged in as woof. And "test again" was sent from woof, so it should be blue when logged in as woof

Edit working code down below, no pdo because I'm not done with this project and I save those for the end to make testing easier.

<?php

include "../Site/db.php";

$url = $_SERVER['REQUEST_URI'];
$urlArray = explode('=', $url);
$Username = $urlArray[sizeof($urlArray) - 1];

$Myself = $_SESSION['username'];

$sql = "SELECT * FROM messages ORDER BY `Id` ASC";
$result = $conn->query($sql);

// Header of message box
echo '<div id="messages" class="messagePersonBox shadow">
        <span class="usersname" name="receiver"><a href="Account?='.$Username.'">'.$Username.'</a></span>
<hr style="margin-top:24px">
<div id="allMessages"class="allMessages">
';

// $sql2 = "SELECT * FROM messages WHERE Sender = '$Myself' ORDER BY `Id` ASC";
// $result2 = $conn->query($sql2);

$sql3 = "SELECT *  FROM messages 
        WHERE (Sender = '$Myself' AND Receiver = '$Username')
           OR (Receiver = '$Myself' AND Sender = '$Username') ORDER BY `MessageTime` ASC";


$result3 = $conn->query($sql3);
print_r($result3);
$x = 0;

$sql4 = "SELECT * FROM messages WHERE Sender = '$Myself'";
$result4 = $conn->query($sql4);

$sql5 = "SELECT * FROM messages WHERE Receiver = '$Myself'";
$result5 = $conn->query($sql5);

$totalSender = mysqli_num_rows($result4);
$totalReceiver = mysqli_num_rows($result5);

// might have to add both totals for while loop
// to get total messages
$totalmessages = mysqli_num_rows($result);

// For receiving
while ($x < $totalmessages) {

    // output data of each row

     if ($result3->num_rows > 0) {
         if ($row = $result3->fetch_assoc()) {
             $Sender = $row['Sender'];
             $Message = $row['Message'];
             $Receiver = $row['Receiver'];
             $TimeSent = $row['MessageTime'];
         }
     }
       $class = $Sender == $Myself ? 'messageDisplay' : 'messageDisplay2';


     // sending a message

         echo '<div id="messages2" class="'.$class.'">'.$Message.'<span style="float: right;margin-top:2px"><font size=1>'.time_elapsed_string($TimeSent).'</span></font></div>';



$x++;
}

// Typing part of message
echo '</div>
      <input type="text" id="messagetosend" name="message" class="messagetype" placeholder="Type a message..."><span id="send" class="messageSend">↩</span>

</div>';
?>

I can add more info if needed.

  • 写回答

1条回答 默认 最新

  • dougu3591 2019-06-21 05:36
    关注

    I suggest you take a step back and restructure this approach a bit.

    For instance, you don't need conversationID (at least not in its current format), as you can deduct it from Sender and Receiver, which is more accurate. You also don't need MessageDate, since MessageTime is a datetime value that holds both the date and the time. So, conversationID and MessageDate can be removed.

    Then, we can clean up the number of queries. You want to get all messages where you are the sender and the other user is the recipient, or where you are the recipient and the other user is the sender of that message. We then sort by date (not the ID!), and check if the message should be green or blue based on the Sender value of that row - set a $class variable with one value for blue if the sender is the current user, green otherwise.

    As a note, when outputting blocks of HTML, you can exit PHP, which makes it easier to read (and deal with quotes). You also had HTML elements with the same ID, which is not allowed.

    You should also be using prepared statements when dealing with variables in a query.

    <?php
    
    include "../Site/db.php";
    
    $url = $_SERVER['REQUEST_URI'];
    $urlArray = explode('=', $url);
    $Username = $urlArray[sizeof($urlArray) - 1];
    
    $Myself = $_SESSION['username'];
    
    $sql = "SELECT Message, MessageTime, Sender, Receiver
            FROM messages 
            WHERE (Sender = ? AND Receiver = ?)
               OR (Receiver = ? AND Sender = ?)
            ORDER BY `MessageTime` ASC");
    if (!$stmt = $conn->prepare($sql)) {
        error_log($conn->error);
        die("An error occurred fetching messages");
    }
    $stmt->bind_param("ssss", $Myself, $Username, $Myself, $Username);
    $stmt->bind_result($message, $timeSent, $sender, $received);
    if (!$stmt->execute()) {
        error_log($stmt->error);
        die("An error occurred fetching messages");
    }
    ?>
    <!-- Header of message box -->
    <div id="messages" class="messagePersonBox shadow">
        <span class="usersname" name="receiver"><a href="Account?=<?php echo $Username; ?>"><?php echo $Username; ?></a></span>
        <hr style="margin-top:24px">
        <div id="allMessages" class="allMessages">
            <?php 
            while ($stmt->fetch()) {
                $class = $sender == $Myself ? 'messageDisplay' : 'messageDisplay1'; // Check which class should be used; if I'm the sender, show messageDisplay, if not show MessageDisplay1 
                ?>
                <div class="<?php echo $class; ?>
                    <?php echo $message; ?>
                    <span style="float: right; margin-top: 2px">
                        <?php echo time_elapsed_string($timeSent); ?>
                    </span>
                </div>
                <?php 
            }
            ?>
        <!-- Typing part of message -->
        </div>
        <input type="text" id="messagetosend" name="message" class="messagetype" placeholder="Type a message..."><span id="send" class="messageSend">↩</span>
    </div>
    <?php 
    $stmt->close();
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 有赏,i卡绘世画不出
  • ¥15 如何用stata画出文献中常见的安慰剂检验图
  • ¥15 c语言链表结构体数据插入
  • ¥40 使用MATLAB解答线性代数问题
  • ¥15 COCOS的问题COCOS的问题
  • ¥15 FPGA-SRIO初始化失败
  • ¥15 MapReduce实现倒排索引失败
  • ¥15 ZABBIX6.0L连接数据库报错,如何解决?(操作系统-centos)
  • ¥15 找一位技术过硬的游戏pj程序员
  • ¥15 matlab生成电测深三层曲线模型代码