【问题标题】:count messages two users in php mysqli在php mysqli中计算两个用户的消息
【发布时间】:2020-01-08 11:17:44
【问题描述】:

我正在 PHP MYSQLI 中创建两个用户之间的消息对话脚本。我想知道如何计算两个用户之间的未读消息。我的脚本没有显示任何内容。

我的数据库 pm 表

id  from_id     to_id    msg               sent_date              read     
1   2           3        hi how are you?   2019-12-05 04:14:20    1                
2   3           2        fine              2019-12-05 05:15:58    0               
3   2           3        hi                2019-12-05 03:20:34    1                  
4   5           2        hi                2019-12-05 08:30:40    0    

这是我的源代码

<?php
$unread_messages = 0;       
if (isset($_SESSION['userid'])) {
    $session_id = $_SESSION['userid'];
}

$sql =  ("SELECT  COUNT(*) AS unread_messages
FROM    pm
WHERE   pm.to_id = ? and pm.from_id=from_id
        AND read = 0");
if ($stmt = $con->prepare($sql)) {
 $stmt->bind_param('i', $session_id);
 $stmt->execute();
}

$result = $stmt->get_result();
if($result->num_rows > 0){
while($row = $result->fetch_assoc()){
    echo $unread_messages;
  }
}
?>

【问题讨论】:

    标签: php mysql sql mysqli


    【解决方案1】:

    我正在创建两个用户之间的消息对话脚本。

    我会这样说:

    select sum(*) cnt_unread
    from pm
    where 
        read = 0
        and (
            (pm.from_id = :userid1 and pm.to_id = :userid2)
            or (pm.from_id = :userid2 and pm.to_id = :userid1)
        )
    

    这将为您提供:userid1:userid2 之间的未读消息计数(无论是从用户 1 到用户 2 还是相反)。

    【讨论】:

    • 显示这样的消息 致命错误:在 C:\xampp\htdocs\demo\npm\cons.php 第 392 行调用布尔值的成员函数 get_result()
    • 我不知道如何添加它可以添加到我的代码中请兄弟
    • @previn:请检查prepare()execute()之后的错误,然后分享相关的SQL错误信息。
    • 我这样添加但只显示零 $sql = ("select sum(seen = 0) cnt_unread from pm where (pm.from_id = from_id and pm.to_id = to_id) or (pm.from_id = from_id 和 pm.to_id = ?)");
    • @previn:请完全按照提供的方式运行查询。我的查询需要两个参数:userid1:userid2,你的只有一个。
    【解决方案2】:
    SET @u1 = 2;  -- id of first user
    SET @u2 = 3;  -- id of 2nd user
    
    SELECT count(`read`) as unread FROM pm 
    WHERE `read` = 0 AND (from_id in (@u1,@u2) OR to_id in (@u1,@u2));
    

    【讨论】:

    • 我检查了只显示零值
    • 第一个问题是使用“read”作为字段名,而它是 mysql 中的关键字。这个问题可以通过用符号`包围来解决,如read
    • 另一个建议是直接使用数据库,直到获得预期结果,然后将 SQL 转移到 PHP 代码。
    猜你喜欢
    • 1970-01-01
    • 2020-04-01
    • 1970-01-01
    • 2019-09-04
    • 1970-01-01
    • 1970-01-01
    • 2017-07-10
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多