我希望更新未读消息的数量,并在用户收到新消息时播放通知声音。 我使用PHP,MySql,Javascript

<!-- Message Notifications -->
        <li class="notifications dropdown">
            <?php
            $total_unread_message_number = 0;
            $current_user = $this->session->userdata('login_type') . '-' . $this->session->userdata('login_user_id');

            $this->db->where('sender', $current_user);
            $this->db->or_where('reciever', $current_user);
            $message_threads = $this->db->get('message_thread')->result_array();
            foreach ($message_threads as $row) {
                $unread_message_number = $this->crud_model->count_unread_message_of_thread($row['message_thread_code']);
                $total_unread_message_number += $unread_message_number;
            }
            ?>
            <a href="#" class="dropdown-toggle" data-toggle="dropdown" data-hover="dropdown" data-close-others="true">
                <i class="entypo-mail"></i>
                <?php if ($total_unread_message_number > 0): ?>
                    <span class="badge badge-info"><?php echo $total_unread_message_number; ?></span>

                <!--Javascript message sound notification-->
                <script>
                $(function(){  

                  $('<audio id="chatAudio"><source src="assets/sounds/notify.ogg" type="audio/ogg"><source src="assets/sounds/notify.mp3" type="audio/mpeg"><source    src="assets/sounds/notify.wav" type="audio/wav"></audio>').appendTo('body');;
                  $('#chatAudio')[0].play();

                  });
                </script>

                <?php endif; ?>
            </a>

The above code is in the header section, hence the notification sound is played when ever the page is reloaded as lond that there is a unread message. But i want it the notification to play immediately the message enters the database.

In that case you need to call a .php file which returns the number of unread messages periodically with AJAX.

The code would look something like this:

var INTERVAL_IN_MILISECONDS = 5000; // 5s
function checkForUnreadMessages() {
    $.get("getUnreadMessagesCount.php")
    .done(function(unreadMessagesCount) {
        if (unreadMessagesCount > 0) {
            $('<audio id="chatAudio"><source src="assets/sounds/notify.ogg" type="audio/ogg"><source src="assets/sounds/notify.mp3" type="audio/mpeg"><source    src="assets/sounds/notify.wav" type="audio/wav"></audio>').appendTo('body');
            $('#chatAudio')[0].play();
        }
    });
}
checkForUnreadMessages();
setInterval(checkForUnreadMessages, INTERVAL_IN_MILISECONDS);