Home  >  Article  >  WeChat Applet  >  WeChat public platform development database operation

WeChat public platform development database operation

高洛峰
高洛峰Original
2017-03-06 09:51:583868browse

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 introduce the MySQL that everyone is familiar with. The database performs operation demonstrations to realize the interaction between WeChat and the database.

It is very simple to use cloud database in BAE application. 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.

Official documentation, please refer to: ttp://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

WeChat public platform development database operation

3.2 Create database

WeChat public platform development database operation

#Note: Each application has and only one database 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 Successfully created

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

Click "phpMyadmin" to access the database.

WeChat public platform development database operation

3.4 phpMyadmin interface

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

WeChat public platform development database operation

3.5 Create a table

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

WeChat public platform development database operation

3.6 Creation Complete

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.

WeChat public platform development database operation

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

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`)
);

phpMyAdmin Operation

WeChat public platform development database operation

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

4. Official example (PHP MySQL)

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

mysql/basic.php file content

<?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,'this is a test message'),
            (2008,'this is another test message'),
            (2009,'xxxxxxxxxxxxxx')";
    $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 = 'yyyyyy' 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['id']} {$row['no']} {$row['name']}<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>";
    }


?>

configure.php file content

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

?>

Test use:

WeChat public platform development database operation

execution succeed.

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

5.1 Create a data table

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

5.2 Insert Data

//插入数据
function _insert_data($sql){
      if(!mysql_query($sql)){
        return 0;    //插入数据失败
    }else{
          if(mysql_affected_rows()>0){
              return 1;    //插入成功
          }else{
              return 2;    //没有行受到影响
          }
    }
}

5.3 Delete data

//删除数据
function _delete_data($sql){
      if(!mysql_query($sql)){
        return 0;    //删除失败
      }else{
          if(mysql_affected_rows()>0){
              return 1;    //删除成功
          }else{
              return 2;    //没有行受到影响
          }
    }
}

5.4 Modify data

//修改数据
function _update_data($sql){
      if(!mysql_query($sql)){
        return 0;    //更新数据失败
    }else{
          if(mysql_affected_rows()>0){
              return 1;    //更新成功;
          }else{
              return 2;    //没有行受到影响
          }
    }
}

5.5 Retrieve data

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

5.6 Delete data table

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

Combine the above functions with the code to connect to the database to generate the mysql_bae.func.php file for the following tests.

6. Test MySQL function usage

6.1 Create a new file dev_mysql.php in the same directory and introduce the mysql_bae.func.php file

require_once './mysql_bae.func.php';

6.2 Test creation table

Delete the test_mysql table created using phpMyAdmin above. The test statement is as follows:

//创建表
$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);

测试正确结果:

WeChat public platform development database operation 

到phpMyAdmin中查看

WeChat public platform development database operation

故意将SQL语句写错

WeChat public platform development database operation

测试错误结果:

WeChat public platform development database operation

6.3 测试插入数据

测试语句如下:

//插入数据
$insert_sql = "insert into test_mysql(from_user, account, password, update_time) values('David','860510', 'abcabc', '2013-09-29 17:14:28')";

$res = _insert_data($insert_sql);
if($res == 1){
    echo "插入成功";
}else{
    echo "插入失败";
}

测试结果:

WeChat public platform development database operation

6.4 测试更新数据

测试语句如下:

//更新数据
$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 "没有行受到影响";
}

测试结果:

WeChat public platform development database operation

再次更新:

WeChat public platform development database operation

6.5 测试删除数据

测试语句如下:

//删除数据
$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 "没有该条记录";
}

测试结果:

WeChat public platform development database operation

再次删除:

WeChat public platform development database operation

6.6 测试检索数据

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

//检索数据
$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>";

}

测试结果:

WeChat public platform development database operation

6.7 测试删除表

测试语句如下:

//删除表$drop_sql = "drop table if exists test_mysql";echo _drop_table($drop_sql);

测试结果:

WeChat public platform development database operation

MySQL 函数测试全部成功。

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

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

1. 绑定+账户+密码
如:绑定+860512+abc123

2. 查询
如:查询

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

4. 删除
如:删除

7.1 引入mysql_bae.func.php 文件

//引入数据库函数文件require_once 'mysql_bae.func.php';

7.2 前置操作

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

$keywords = explode("+",$keyword);

B. 获取当前时间

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

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

//判断是否已经绑定
$select_sql="SELECT id from test_mysql WHERE from_user='$fromUsername'";
$res=_select_data($select_sql);
$rows=mysql_fetch_array($res, MYSQL_ASSOC);
if($rows[id]  ''){
        $user_flag='y';          
}

7.3 测试插入操作

测试代码:

if(trim($keywords[0] == '绑定')){
    if($user_flag  'y'){
        $insert_sql="INSERT INTO test_mysql(from_user, account, password, update_time) VALUES('$fromUsername','$keywords[1]','$keywords[2]','$nowtime')";
        $res = _insert_data($insert_sql);
        if($res == 1){
            $contentStr = "绑定成功";
        }elseif($res == 0){
            $contentStr = "绑定失败";
        }
    }else{
        $contentStr = "该账户已绑定";
    }
}

测试结果:

WeChat public platform development database operation

7.4 测试查询操作

测试代码:

if(trim($keywords[0] == '查询')){
    $select_sql="SELECT * FROM test_mysql WHERE from_user='$fromUsername'";
    $select_res=_select_data($select_sql);
    $rows=mysql_fetch_assoc($select_res);
    if($rows[id]  ''){
    $contentStr="账户:$rows[account]\n"."密码:$rows[password]\n"."From_user:$rows[from_user]\n"."更新时间:$rows[update_time]";
    }else{
    $contentStr="您还未绑定账户,查询不到相关信息,请先绑定,谢谢!";
    }
}

测试结果:

WeChat public platform development database operation

7.5 测试更新操作

测试代码:

if(trim($keywords[0] == "修改")){
    $old_password=$keywords[1];
    $new_password=$keywords[2];
    $select_password_sql="SELECT * FROM test_mysql WHERE from_user='$fromUsername'";
    $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='$new_password' WHERE from_user='$fromUsername'";
        $res = _update_data($update_sql);
        if($res == 1){
            $contentStr = "修改成功";
        }elseif($res == 0){
            $contentStr = "修改失败";
        }
    }else{
        $contentStr = "原密码有误,请确认后重试";
    }
}

测试结果:

WeChat public platform development database operation

7.6 测试删除操作

测试代码:

if(trim($keywords[0] == "删除")){
    $delete_sql="DELETE FROM test_mysql WHERE from_user='$fromUsername'";
    $res = _delete_data($delete_sql);
    if($res == 1){
        $contentStr = "删除成功";
    }elseif($res == 0){
        $contentStr = "删除失败";
    }
}

测试结果:

WeChat public platform development database operation

与微信的交互测试成功。

八、PHP Mysqli 扩展,封装成类

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

<?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('HTTP_BAE_ENV_ADDR_SQL_IP');
        $this->user = getenv('HTTP_BAE_ENV_AK');
        $this->password = getenv('HTTP_BAE_ENV_SK');
        $this->port = getenv('HTTP_BAE_ENV_ADDR_SQL_PORT');

        $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();
    }
}
?>

九、测试类的使用

9.1 测试DML操作

测试代码:

<?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 "没有行数影响";
}
?>

测试结果:

WeChat public platform development database operation

9.2 测试DQL操作

测试代码:

<?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 '<br>';
}

$res->free();
?>

测试结果:

WeChat public platform development database operation

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

10.1 前置操作

A. 引入MySQLi_BAE.class.php 文件

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

B. 实例化对象

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

10.2 测试插入操作

测试代码:

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

测试结果:

WeChat public platform development database operation

10.3 测试查询操作

测试代码:

$select_sql="SELECT * FROM test_mysql WHERE from_user='$fromUsername'";
$select_res=$this->mysqli_BAE->execute_dql($select_sql);
$rows=$select_res->fetch_array(MYSQLI_ASSOC);

测试结果:

WeChat public platform development database operation

10.4 测试更新操作

测试代码:

$update_sql="UPDATE test_mysql SET password='$new_password' WHERE from_user='$fromUsername'"; 
$res = $this->mysqli_BAE->execute_dml($update_sql);

测试结果:

WeChat public platform development database operation

10.5 测试删除操作

测试代码:

$delete_sql="DELETE FROM test_mysql WHERE from_user='$fromUsername'";
$res = $this->mysqli_BAE->execute_dml($delete_sql);

测试结果:

WeChat public platform development database operation

与微信交互测试成功。 

更多WeChat public platform development database operation相关文章请关注PHP中文网!


Statement:
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