我如何将两个num_rows一起添加?

时间:2015-02-07 20:51:18

标签: php

我的PHP代码有点麻烦。

我想将两个num_rows一起添加到顶部导航栏中。

我的代码如下:

$get_unread_query = mysqli_query($con,"SELECT opened FROM pvt_messages WHERE user_to='$user' && opened='no'");
$get_unread_rows = mysqli_fetch_assoc($get_unread_query);
$unread_numrows = mysqli_num_rows($get_unread_query);
$unread_numrows = "(".$unread_numrows.")";

$friendRequests = mysqli_query($con,"SELECT * FROM friend_requests WHERE user_to='$user'");
$friend_numrows = mysqli_num_rows($friendRequests);
$friend_numrows = "(".$friend_numrows.")";

$notifications = $unread_numrows + $friend_numrows;
$notifications = "(".$notifications.")";

正如您所见$notifications = $unread_numrows + $friend_numrows

这应该将$ unread_numrows添加到$ friend_numrows并显示结果。

例如,如果$ unread_numrows保持1且$ friend_numrows也保持1,则结果将在顶部导航栏中显示2。

正如大多数人所知,这段代码不起作用。那我怎么能让它发挥作用呢?

感谢任何帮助!

感谢。

2 个答案:

答案 0 :(得分:2)

你的问题是你用一个字符串“()”包装你的数字.. 您可以在计算总和之后执行此操作:

$get_unread_query = mysqli_query($con,"SELECT opened FROM pvt_messages WHERE user_to='$user' && opened='no'");
$get_unread_rows = mysqli_fetch_assoc($get_unread_query);
$unread_numrows = mysqli_num_rows($get_unread_query); // number

$friendRequests = mysqli_query($con,"SELECT * FROM friend_requests WHERE user_to='$user'");
$friend_numrows = mysqli_num_rows($friendRequests); // number

$notifications = $unread_numrows + $friend_numrows; // number

// now you can turn them all to strings
$notifications = "(".$notifications.")";
$unread_numrows = "(".$unread_numrows.")";
$friend_numrows = "(".$friend_numrows.")";

答案 1 :(得分:0)

$ notification是因为行:

$notifications = $unread_numrows + $friend_numrows;

声明为int double,但不是String。

在下一行中,您将其视为字符串可能会尝试:

$sum = $unread_numrows + $friend_numrows;
$notifications = "(" + $sum + ")"