Home > Backend Development > PHP Tutorial > WeChat public platform development - database operation_PHP tutorial

WeChat public platform development - database operation_PHP tutorial

WBOY
Release: 2016-07-13 10:35:40
Original
1175 people have browsed it

[PHP WeChat public platform development series]

01. Configure WeChat interface
02. Public platform sample code analysis
03. Subscription event (subscribe) processing
04. Development of simple reply function
05. Weather forecast function development
06.Translation function development
07. Chatbot function development
08. Custom menu function
09. Database operations


URL of this article: http://www.phpchina.com/archives/view-43411-1.html
This series is contributed by PHPChina's specially invited author @David_Tang. Please indicate the author's information and the address of this article when reprinting.

1. Introduction

The function development explained earlier is completed by simply calling the API, without operating the database. In the subsequent development of advanced functions, a database will need to be used, so in this article, a brief introduction to the operation of the MySQL database will be provided for readers' reference.

2. Idea analysis

Baidu Developer Center provides powerful cloud databases (including MySQL, MongoDB, Redis). In this tutorial, we will demonstrate the operation of the familiar MySQL database to realize the interaction between WeChat and the database.

It is very simple to use cloud databases in BAE applications. The name in the database list is the dbname when connecting to the database. The username, password, connection address and port are retrieved through environment variables in the application.

You can use the standard PHP Mysql or PHP Mysqli extension to access the database. These two extensions are already provided in BAE's PHP and can be used directly by the application.

For official documentation, please refer to: http://developer.baidu.com/wiki/index.php?title=docs/cplat/rt/mysql

3. Create BAE MySQL database

3.1 Log in to Baidu Developer Center -> Management Center -> Select Application -> Cloud Environment -> Service Management -> MySQL (Cloud Database) -> Create Database

3.2 Create database

Note: Each application has only one database that enjoys the 1G free quota, and the other databases do not enjoy the free quota discount. This offer can only be used again if the database that has used the free quota is deleted.

3.3 Created successfully

Here you can see the name of the database, which is dbname, which will be used later.

Click on “phpMyadmin” to access the database.

3.4 phpMyadmin interface

Create a new data table, enter the table name and number of fields, and click "Execute" to create the table.

3.5 Create table

Enter the field name and field type. After completing the input, click "Save" below to complete the creation of the table.

3.6 Creation completed

Modify the id field as the primary key and add AUTO_INCREMENT; modify the from_user field to unique (UNIQUE) to complete the modification of the table.

The table creation operation can also be completed using the following SQL statement:

WeChat public platform development - database operation_PHP tutorial
CREATE TABLE IF NOT EXISTS `test_mysql` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `from_user` varchar(40) DEFAULT NULL,
  `account` varchar(40) DEFAULT NULL,
  `password` varchar(40) DEFAULT NULL,
  `update_time` datetime DEFAULT NULL,
  PRIMARY KEY (`id`),
  UNIQUE KEY `from_user` (`from_user`)
);
Copy after login
WeChat public platform development - database operation_PHP tutorial

phpMyAdmin operations

The creation of the database and data tables ends here. Next, we will write code to explain in detail the use of the database and data tables.

4. Official example (PHP MySQL)

The demo (PHP MySQL) example officially provided by BAE is as follows:

mysql/basic.php file content

WeChat public platform development - database operation_PHP tutorial
<?php
/**
 * MySQL示例,通过该示例可熟悉BAE平台MySQL的使用(CRUD)
 */
require_once("../configure.php");
    /*替换为你自己的数据库名(可从管理中心查看到)*/
    $dbname = MYSQLNAME;
     
    /*从环境变量里取出数据库连接需要的参数*/
    $host = getenv(&#39;HTTP_BAE_ENV_ADDR_SQL_IP&#39;);
    $port = getenv(&#39;HTTP_BAE_ENV_ADDR_SQL_PORT&#39;);
    $user = getenv(&#39;HTTP_BAE_ENV_AK&#39;);
    $pwd = getenv(&#39;HTTP_BAE_ENV_SK&#39;);
    
    /*接着调用mysql_connect()连接服务器*/
    $link = @mysql_connect("{$host}:{$port}",$user,$pwd,true);
    if(!$link) {
      die("Connect Server Failed: " . mysql_error());
    }
    /*连接成功后立即调用mysql_select_db()选中需要连接的数据库*/
    if(!mysql_select_db($dbname,$link)) {
      die("Select Database Failed: " . mysql_error($link));
    }
    /*至此连接已完全建立,就可对当前数据库进行相应的操作了*/
    /*!!!注意,无法再通过本次连接调用mysql_select_db来切换到其它数据库了!!!*/
    /* 需要再连接其它数据库,请再使用mysql_connect+mysql_select_db启动另一个连接*/
     
    /**
    * 接下来就可以使用其它标准php mysql函数操作进行数据库操作
    */
    
    //创建一个数据库表
    $sql = "create table if not exists test_mysql(
            id int primary key auto_increment,
            no int, 
            name varchar(1024),
            key idx_no(no))";
    $ret = mysql_query($sql, $link);
    if ($ret === false) {
        die("Create Table Failed: " . mysql_error($link));
    } else {
        echo "Create Table Succeed<br />";
    }
    
    //插入数据
    $sql = "insert into test_mysql(no, name) values(2007,&#39;this is a test message&#39;),
            (2008,&#39;this is another test message&#39;),
            (2009,&#39;xxxxxxxxxxxxxx&#39;)";
    $ret = mysql_query($sql, $link);
    if ($ret === false) {
        die("Insert Failed: " . mysql_error($link));
    } else {
        echo "Insert Succeed<br />";
    }
    
    //删除数据
    $sql = "delete from test_mysql where no = 2008";
    $ret = mysql_query($sql, $link);
    if ($ret === false) {
        die("Delete Failed: " . mysql_error($link));
    } else {
        echo "Delete  Succeed<br />";
    }
    
    //修改数据
    $sql = "update test_mysql set name = &#39;yyyyyy&#39; where no = 2009";
    $ret = mysql_query($sql, $link);
    if ($ret === false) {
        die("Update Failed: " . mysql_error($link));
    } else {
        echo "Update Succeed<br />";
    }
    
    
    //检索数据
    $sql = "select id,no,name from test_mysql";
    $ret = mysql_query($sql, $link);
    if ($ret === false) {
        die("Select Failed: " . mysql_error($link));
    } else {
        echo "Select Succeed<br />";
        while ($row = mysql_fetch_assoc($ret)) {
            echo "{$row[&#39;id&#39;]} {$row[&#39;no&#39;]} {$row[&#39;name&#39;]}<br />";
        }
    }
    
    //删除表
    $sql = "drop table if exists test_mysql";
    $ret = mysql_query($sql, $link);
    if ($ret === false) {
        die("Drop Table Failed: " . mysql_error($link));
    } else {
        echo "Drop Table Succeed<br />";
    }


?>
Copy after login
WeChat public platform development - database operation_PHP tutorial

configure.php file content

<?php

    /***配置数据库名称***/
    define("MYSQLNAME", "qzMlSkByflhScPCOFtax");

?>
Copy after login

Test use:

Execution successful.

5. Modify it into a callable function form (PHP MySQL)

5.1 Create data table

//创建一个数据库表
function _create_table($sql){
    mysql_query($sql) or die(&#39;创建表失败,错误信息:&#39;.mysql_error());
    return "创建表成功";
}
Copy after login

5.2 Insert data

WeChat public platform development - database operation_PHP tutorial
//插入数据
function _insert_data($sql){
      if(!mysql_query($sql)){
        return 0;    //插入数据失败
    }else{
          if(mysql_affected_rows()>0){
              return 1;    //插入成功
          }else{
              return 2;    //没有行受到影响
          }
    }
}
Copy after login
WeChat public platform development - database operation_PHP tutorial

5.3 Delete data

WeChat public platform development - database operation_PHP tutorial
//删除数据
function _delete_data($sql){
      if(!mysql_query($sql)){
        return 0;    //删除失败
      }else{
          if(mysql_affected_rows()>0){
              return 1;    //删除成功
          }else{
              return 2;    //没有行受到影响
          }
    }
}
Copy after login
WeChat public platform development - database operation_PHP tutorial

5.4 Modify data

WeChat public platform development - database operation_PHP tutorial
//修改数据
function _update_data($sql){
      if(!mysql_query($sql)){
        return 0;    //更新数据失败
    }else{
          if(mysql_affected_rows()>0){
              return 1;    //更新成功;
          }else{
              return 2;    //没有行受到影响
          }
    }
}
Copy after login
WeChat public platform development - database operation_PHP tutorial

5.5 检索数据

//检索数据
function _select_data($sql){
    $ret = mysql_query($sql) or die(&#39;SQL语句有错误,错误信息:&#39;.mysql_error());
    return $ret;
}
Copy after login

5.6 删除数据表

//删除表
function _drop_table($sql){
    mysql_query($sql) or die(&#39;删除表失败,错误信息:&#39;.mysql_error());
    return "删除表成功";
}
Copy after login

将以上函数和连接数据库的代码结合起来,生成mysql_bae.func.php 文件,供下面测试使用。

六、测试MySQL 函数使用

6.1 新建文件dev_mysql.php 在同一目录下并引入mysql_bae.func.php 文件

require_once &#39;./mysql_bae.func.php&#39;;
Copy after login

6.2 测试创建表

将上面使用phpMyAdmin 创建的test_mysql 表删除,测试语句如下:

WeChat public platform development - database operation_PHP tutorial
//创建表
$create_sql = "CREATE TABLE IF NOT EXISTS `test_mysql` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `from_user` varchar(40) DEFAULT NULL,
  `account` varchar(40) DEFAULT NULL,
  `password` varchar(40) DEFAULT NULL,
  `update_time` datetime DEFAULT NULL,
  PRIMARY KEY (`id`),
  UNIQUE KEY `from_user` (`from_user`)
)";

echo _create_table($create_sql);
Copy after login
WeChat public platform development - database operation_PHP tutorial

测试正确结果:

到phpMyAdmin中查看

故意将SQL语句写错

测试错误结果:

6.3 测试插入数据

测试语句如下:

WeChat public platform development - database operation_PHP tutorial
//插入数据
$insert_sql = "insert into test_mysql(from_user, account, password, update_time) values(&#39;David&#39;,&#39;860510&#39;, &#39;abcabc&#39;, &#39;2013-09-29 17:14:28&#39;)";

$res = _insert_data($insert_sql);
if($res == 1){
    echo "插入成功";
}else{
    echo "插入失败";
}
Copy after login
WeChat public platform development - database operation_PHP tutorial

测试结果:

6.4 测试更新数据

测试语句如下:

WeChat public platform development - database operation_PHP tutorial
//更新数据
$update_sql = "update test_mysql set account = 860512 where account = 860510";

$res = _update_data($update_sql);
if($res == 1){
    echo "更新成功";
}elseif($res == 0){
    echo "更新失败";
}elseif($res == 2){
    echo "没有行受到影响";
}
Copy after login
WeChat public platform development - database operation_PHP tutorial

测试结果:

再次更新:

6.5 测试删除数据

测试语句如下:

WeChat public platform development - database operation_PHP tutorial
//删除数据
$delete_sql = "delete from test_mysql where account = 860512";

$res = _delete_data($delete_sql);
if($res == 1){
    echo "删除成功";
}elseif($res == 0){
    echo "删除失败";
}elseif($res == 2){
    echo "没有该条记录";
}
Copy after login
WeChat public platform development - database operation_PHP tutorial

测试结果:

再次删除:

6.6 测试检索数据

再次执行上面的插入操作做检索测试,测试语句如下:

WeChat public platform development - database operation_PHP tutorial
//检索数据
$select_sql = "select * from test_mysql";

$result = _select_data($select_sql);

while($rows = mysql_fetch_array($result,MYSQL_ASSOC)){

    echo $rows[id]."--".$rows[from_user]."--".$rows[account]."--".$rows[password]."--".$rows[update_time];
    echo "<br />";

}
Copy after login
WeChat public platform development - database operation_PHP tutorial

测试结果:

6.7 测试删除表

测试语句如下:

//删除表
$drop_sql = "drop table if exists test_mysql";

echo _drop_table($drop_sql);
Copy after login

测试结果:

MySQL 函数测试全部成功。

七、实现与微信的交互(Mysql 扩展)

保证数据库中存在test_msyql表,这里测试微信对MySQL数据库的增删改查操作,不考虑特殊情况,只按照下面的方法测试:

WeChat public platform development - database operation_PHP tutorial
1. 绑定+账户+密码
如:绑定+860512+abc123

2. 查询
如:查询

3. 修改+旧密码+新密码
如:修改+abc123+123456

4. 删除
如:删除
Copy after login
WeChat public platform development - database operation_PHP tutorial

7.1 引入mysql_bae.func.php 文件

//引入数据库函数文件
require_once &#39;mysql_bae.func.php&#39;;
Copy after login

7.2 前置操作

A. 将输入的语句拆分成数组,以“+”号分隔

$keywords = explode("+",$keyword);
Copy after login

B. 获取当前时间

//获取当前时间
$nowtime=date("Y-m-d G:i:s");
Copy after login

C. 判断用户是否已经绑定

WeChat public platform development - database operation_PHP tutorial
//判断是否已经绑定
$select_sql="SELECT id from test_mysql WHERE from_user=&#39;$fromUsername&#39;";
$res=_select_data($select_sql);
$rows=mysql_fetch_array($res, MYSQL_ASSOC);
if($rows[id] <> &#39;&#39;){
        $user_flag=&#39;y&#39;;          
}
Copy after login
WeChat public platform development - database operation_PHP tutorial

7.3 测试插入操作

测试代码:

WeChat public platform development - database operation_PHP tutorial
if(trim($keywords[0] == &#39;绑定&#39;)){
    if($user_flag <> &#39;y&#39;){
        $insert_sql="INSERT INTO test_mysql(from_user, account, password, update_time) VALUES(&#39;$fromUsername&#39;,&#39;$keywords[1]&#39;,&#39;$keywords[2]&#39;,&#39;$nowtime&#39;)";
        $res = _insert_data($insert_sql);
        if($res == 1){
            $contentStr = "绑定成功";
        }elseif($res == 0){
            $contentStr = "绑定失败";
        }
    }else{
        $contentStr = "该账户已绑定";
    }
}
Copy after login
WeChat public platform development - database operation_PHP tutorial

测试结果:

WeChat public platform development - database operation_PHP tutorial

7.4 测试查询操作

测试代码:

WeChat public platform development - database operation_PHP tutorial
if(trim($keywords[0] == &#39;查询&#39;)){
    $select_sql="SELECT * FROM test_mysql WHERE from_user=&#39;$fromUsername&#39;";
    $select_res=_select_data($select_sql);
    $rows=mysql_fetch_assoc($select_res);
    if($rows[id] <> &#39;&#39;){
    $contentStr="账户:$rows[account]\n"."密码:$rows[password]\n"."From_user:$rows[from_user]\n"."更新时间:$rows[update_time]";
    }else{
    $contentStr="您还未绑定账户,查询不到相关信息,请先绑定,谢谢!";
    }
}
Copy after login
WeChat public platform development - database operation_PHP tutorial

测试结果:

WeChat public platform development - database operation_PHP tutorial

7.5 测试更新操作

测试代码:

WeChat public platform development - database operation_PHP tutorial
if(trim($keywords[0] == "修改")){
    $old_password=$keywords[1];
    $new_password=$keywords[2];
    $select_password_sql="SELECT * FROM test_mysql WHERE from_user=&#39;$fromUsername&#39;";
    $select_res=_select_data($select_password_sql);
    $rows=mysql_fetch_assoc($select_res);
    if($old_password == $rows[password]){
        $update_sql="UPDATE test_mysql SET password=&#39;$new_password&#39; WHERE from_user=&#39;$fromUsername&#39;";
        $res = _update_data($update_sql);
        if($res == 1){
            $contentStr = "修改成功";
        }elseif($res == 0){
            $contentStr = "修改失败";
        }
    }else{
        $contentStr = "原密码有误,请确认后重试";
    }
}
Copy after login
WeChat public platform development - database operation_PHP tutorial

测试结果:

WeChat public platform development - database operation_PHP tutorial

7.6 测试删除操作

测试代码:

WeChat public platform development - database operation_PHP tutorial
if(trim($keywords[0] == "删除")){
    $delete_sql="DELETE FROM test_mysql WHERE from_user=&#39;$fromUsername&#39;";
    $res = _delete_data($delete_sql);
    if($res == 1){
        $contentStr = "删除成功";
    }elseif($res == 0){
        $contentStr = "删除失败";
    }
}
Copy after login
WeChat public platform development - database operation_PHP tutorial

测试结果:

WeChat public platform development - database operation_PHP tutorial

与微信的交互测试成功。

八、PHP Mysqli 扩展,封装成类

将Mysqli 扩展封装成类使用,代码如下:

WeChat public platform development - database operation_PHP tutorial
<?php

require_once &#39;includes/configure.php&#39;;

class MySQLi_BAE{

    private $mysqli;
    private $host;
    private $user;
    private $password;
    private $port;
    private $database;

    //在类之外访问私有变量时使用
    function __get($property_name){
        if(isset($this->$property_name)){
            return($this->$property_name);
        }else{
            return(NULL);
        }    
    }

    function __set($property_name, $value){
        $this->$property_name=$value;
    }

    function __construct(){

        /*从平台获取查询要连接的数据库名称*/
        $this->database = MYSQLNAME;

        /*从环境变量里取出数据库连接需要的参数*/
        $this->host = getenv(&#39;HTTP_BAE_ENV_ADDR_SQL_IP&#39;);
        $this->user = getenv(&#39;HTTP_BAE_ENV_AK&#39;);
        $this->password = getenv(&#39;HTTP_BAE_ENV_SK&#39;);
        $this->port = getenv(&#39;HTTP_BAE_ENV_ADDR_SQL_PORT&#39;);

        $this->mysqli = new mysqli($this->host, $this->user, $this->password, $this->database, $this->port);
        if($this->mysqli->connect_error){
            die("Connect Server Failed:".$this->mysqli->error);
        }
        
        $this->mysqli->query("set names utf8");
    }

    //dql statement
    function execute_dql($query){
        
        $res = $this->mysqli->query($query) or die("操作失败".$this->mysqli->error);
        return $res;
        
        //$this->mysqli->close();
    }

    //dml statement
    function execute_dml($query){
        
        $res = $this->mysqli->query($query) or die("操作失败".$this->mysqli->error);
        
        if(!$res){
            return 0;//失败
        }else{
            if($this->mysqli->affected_rows > 0){
                return 1;//执行成功
            }else{
                return 2;//没有行受影响
            }
        }
    
        //$this->mysqli->close();
    }
}
?>
Copy after login
WeChat public platform development - database operation_PHP tutorial

九、测试类的使用

9.1 测试DML操作

测试代码:

WeChat public platform development - database operation_PHP tutorial
<?php

require_once "MySQLi_BAE.class.php";

$mysqli_BAE=new MySQLi_BAE();


//**************dml*******************
$sql="insert into test_mysql (from_user, account, password, update_time) values(&#39;David&#39;,&#39;860510&#39;, &#39;abcabc&#39;, &#39;2013-09-27 17:14:28&#39;)";

//$sql="update test_mysql set account = 860512 where account = 860510";

//$sql="delete from test_mysql where account = 860512";

$res=$mysqli_BAE->execute_dml($sql);

if($res==0){
    echo "执行失败";
}elseif($res==1){
    echo "执行成功";
}else{
    echo "没有行数影响";
}
?>
Copy after login
WeChat public platform development - database operation_PHP tutorial

测试结果:

WeChat public platform development - database operation_PHP tutorial

9.2 测试DQL操作

测试代码:

WeChat public platform development - database operation_PHP tutorial
<?php

require_once "MySQLi_BAE.class.php";

$mysqli_BAE=new MySQLi_BAE();

//**************dql******************
$sql="select * from test_mysql";

$res=$mysqli_BAE->execute_dql($sql);

while($row=$res->fetch_row()){
    
    foreach($row as $key=>$val){
        echo "$val--";
    }
    echo &#39;<br/>&#39;;
}

$res->free();
?>
Copy after login
WeChat public platform development - database operation_PHP tutorial

测试结果:

WeChat public platform development - database operation_PHP tutorial

十、实现与微信的交互(Mysqli 扩展)

10.1 前置操作

A. 引入MySQLi_BAE.class.php 文件

//引入数据库函数文件
require_once "MySQLi_BAE.class.php";
Copy after login

B. 实例化对象

public function __construct()
{
    $this->mysqli_BAE=new MySQLi_BAE();
}
Copy after login

10.2 测试插入操作

测试代码:

$insert_sql="INSERT INTO test_mysql(from_user, account, password, update_time) VALUES(&#39;$fromUsername&#39;,&#39;$keywords[1]&#39;,&#39;$keywords[2]&#39;,&#39;$nowtime&#39;)";
$res = $this->mysqli_BAE->execute_dml($insert_sql);
Copy after login

测试结果:

WeChat public platform development - database operation_PHP tutorial

10.3 测试查询操作

测试代码:

$select_sql="SELECT * FROM test_mysql WHERE from_user=&#39;$fromUsername&#39;";
$select_res=$this->mysqli_BAE->execute_dql($select_sql);
$rows=$select_res->fetch_array(MYSQLI_ASSOC);
Copy after login

测试结果:

WeChat public platform development - database operation_PHP tutorial

10.4 测试更新操作

测试代码:

$update_sql="UPDATE test_mysql SET password=&#39;$new_password&#39; WHERE from_user=&#39;$fromUsername&#39;"; 
$res = $this->mysqli_BAE->execute_dml($update_sql);
Copy after login

测试结果:

WeChat public platform development - database operation_PHP tutorial

10.5 测试删除操作

测试代码:

$delete_sql="DELETE FROM test_mysql WHERE from_user=&#39;$fromUsername&#39;";
$res = $this->mysqli_BAE->execute_dml($delete_sql);
Copy after login

测试结果:

WeChat public platform development - database operation_PHP tutorial

与微信交互测试成功。 

www.bkjia.comtruehttp://www.bkjia.com/PHPjc/742553.htmlTechArticle【PHP微信公众平台开发系列】 01.配置微信接口 02.公众平台示例代码分析 03.订阅事件(subscribe)处理 04.简单回复功能开发 05.天气预报功能...
Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template