php+ajax實現微信上牆

很久就想實現這個功能了,但是一直沒心情,好在收到網易實習的offer,因而心情大好,實現了這個功能來和你們共享。你們能夠先看效果吧:只要關注微信公衆賬號say_magic,php

                                                                                   

而後打開網址http://saymaic.sinaapp.com/weixin/wall.php,在公衆號裏回覆:上牆+您要說的話,您就會發現您說的話會同步到上面的網址上。html


整個流程大概是這樣:mysql

公衆號的後臺接收到消息並將消息存入數據庫,而前臺呢,則使用js的setTimeout函數進行循環的使用ajax向後臺get數據來獲取數據庫的最新數據,當明白整個原理後,就顯得很簡單,接下來看一下主要的代碼:jquery

wall.php(微信牆頁面 )web

<?php
     include_once("sql.php");
?>
<!doctype html>
<html>
<head>
<meta charset="utf-8" />
<title>微信牆</title>
<style>
    
#msgBox div {
	padding: 19px;
	margin-bottom: 20px;
	background: #aaaaaa;
	border: 2px solid #e3e3e3;
	-webkit-border-radius: 4px;
	-moz-border-radius: 4px;
	border-radius: 4px;
	-webkit-box-shadow: inset 0 1px 1px rgba(0,0,0,0.05);
	-moz-box-shadow: inset 0 1px 1px rgba(0,0,0,0.05);
	box-shadow: inset 0 1px 1px rgba(0,0,0,0.05);
    filter:alpha(opacity=60);
     /* CSS3 standard */
     opacity:0.4;
     font-style:italic;
     font-size:15px;
     width:50%;
}
    
body{
	background: url(bg_main.jpg);
}
</style>
</head>
<body>
    <center>
<div id="msgBox">
<?php
$wxQuery = 'SELECT * FROM wx_note ORDER BY id DESC LIMIT 25';//把wx_msg更改掉
$wxResult =$mysql->query($wxQuery);
while ($wxRow=mysql_fetch_row($wxResult)) {
    $lastID or $lastID = $wxRow[0];//0表明數據庫中的id,這個要和你本身數據庫相對應
    $content = $wxRow[4];//4也是同樣的
	echo '<div>',$content,"</div>\n";
}
$lastID = (int)$lastID;
?>
</div>
 
<script src="http://ajax.aspnetcdn.com/ajax/jQuery/jquery-1.8.3.min.js"></script>
<script>
var lastID = <?php echo $lastID; ?>;
function getMessages() {
       $.ajax({
           url: "message.php?lastID=" + lastID + "&v=" + (new Date()/1),
        dataType: "json",
        error: function(){  
            alert('Error loading JSON document');  
        },  
        success: function(data){//若是調用php成功            
				$.each(data,function(i,n){
                        message = '<div>' + n + '</div>';
                        $(message).prependTo('#msgBox').hide().slideDown('slow');
                       	lastID = i;
				});


        }
    });	
	window.setTimeout(getMessages, 5000);
}
getMessages();
</script>
 </center>
</body>
</html>

mysql操做文件sql.php:

<?php
$hostname = '***********';
$dbuser = '***********';
$dbpass = '***************';
$dbname = '************'; 
$mysql = new mysql( $hostname,$dbuser,$dbpass,$dbname,'','');

class mysql {
    private $db_host; //數據庫主機
    private $db_user; //數據庫用戶名
    private $db_pwd; //數據庫用戶名密碼
    private $db_database; //數據庫名
    private $conn; //數據庫鏈接標識;
    private $result; //執行query命令的結果資源標識
    private $sql; //sql執行語句
    private $row; //返回的條目數
    private $coding; //數據庫編碼,GBK,UTF8,gb2312
    private $bulletin = true; //是否開啓錯誤記錄
    private $show_error = false; //測試階段,顯示全部錯誤,具備安全隱患,默認關閉
    private $is_error = false; //發現錯誤是否當即終止,默認true,建議不啓用,由於當有問題時用戶什麼也看不到是很苦惱的
  
    /*構造函數*/
    public function __construct($db_host, $db_user, $db_pwd, $db_database, $conn, $coding) {
        $this->db_host = $db_host;
        $this->db_user = $db_user;
        $this->db_pwd = $db_pwd;
        $this->db_database = $db_database;
        $this->conn = $conn;
        $this->coding = $coding;
        $this->connect();
    }
  
    /*數據庫鏈接*/
    public function connect() {
        if ($this->conn == "pconn") {
            //永久連接
            $this->conn = mysql_pconnect($this->db_host, $this->db_user, $this->db_pwd);
        } else {
            //即便連接
            $this->conn = mysql_connect($this->db_host, $this->db_user, $this->db_pwd);
        }
  
        if (!mysql_select_db($this->db_database, $this->conn)) {
            if ($this->show_error) {
                $this->show_error("數據庫不可用:", $this->db_database);
            }
        }
        //mysql_query("SET NAMES $this->coding");
    }
  
    /*數據庫執行語句,可執行查詢添加修改刪除等任何sql語句*/
    public function query($sql) {
        if ($sql == "") {
            $this->show_error("SQL語句錯誤:", "SQL查詢語句爲空");
        }
        $this->sql = $sql;
        $result = mysql_query($this->sql, $this->conn);


        if (!$result) {


            //調試中使用,sql語句出錯時會自動打印出來
            if ($this->show_error) {
                $this->show_error("錯誤SQL語句:", $this->sql);
            }
        } else {
             $this->result = $result;
        }
        return $this->result;
    }
  
}
?>


不斷從數據庫獲取最新數據的文件message.php.
ajax


<?php
 header('Content-Type:text/html; charset=UTF-8');//utf-8,使中文不會變成亂碼
/**************************************************************
 *
 *	使用特定function對數組中全部元素作處理
 *	@param	string	&$array		要處理的字符串
 *	@param	string	$function	要執行的函數
 *	@return boolean	$apply_to_keys_also		是否也應用到key上
 *	@access public
 *
 *************************************************************/
function arrayRecursive(&$array, $function, $apply_to_keys_also = false)
{
    static $recursive_counter = 0;
    if (++$recursive_counter > 1000) {
        die('possible deep recursion attack');
    }
    foreach ($array as $key => $value) {
        if (is_array($value)) {
            arrayRecursive($array[$key], $function, $apply_to_keys_also);
        } else {
            $array[$key] = $function($value);
        }
 
        if ($apply_to_keys_also && is_string($key)) {
            $new_key = $function($key);
            if ($new_key != $key) {
                $array[$new_key] = $array[$key];
                unset($array[$key]);
            }
        }
    }
    $recursive_counter--;
}


function JSON($array) {
	arrayRecursive($array, 'urlencode', true);
	$json = json_encode($array);
	return urldecode($json);
}


$lastID = (int) $_GET['lastID'];
include_once("sql.php");
$backValue=array();


$wxQuery = "SELECT * FROM wx_note WHERE id > ".$lastID." ORDER BY id LIMIT  3";
$wxResult = $mysql->query($wxQuery);
while ($wxRow=mysql_fetch_row($wxResult)) {
	$recordID = $wxRow[0];
	$content = $wxRow[4];
    //$xml=$content;
    $backValue[$recordID ] = $content;


}


echo JSON($backValue);


?>


最後,若是須要的話,還有背景圖片: http://www.saymagic.cn/weixin/bg_main.jpg .


固然,這裏說的只是後端的部分,在處理微信消息上,你還須要把收到的消息存入數據庫,這應該沒什麼難度,就不放代碼了。這裏必定要記得和剛纔操做的方法中的數據格式相對應,這是最容易出錯的了。好的,若是有什麼疑問的話,歡迎留言。sql


                                                轉載請註明:個人原博客連接http://www.saymagic.cn/blog.php?id=58


版權聲明:本文爲博主原創文章,未經博主容許不得轉載。數據庫

相關文章
相關標籤/搜索