swoole组件----mysql查询,插入数据

注意!任何swoole函数都应该包含在go(function(){})

  • 经典查询方法query()
go(function (){
    $swoole_mysql = new SwooleCoroutineMySQL();
    $swoole_mysql->connect([
        'host' => '127.0.0.1',
        'port' => 3306,
        'user' => 'root',
        'password' => 'xxxx',
        'database' => 'xxxxdb',
    ]);
    $res = $swoole_mysql->query('select * from colname');
    if($res === false) {
        return;
    }
    foreach ($res as $value) {
        echo $value['comment'].PHP_EOL;
    }
});
  • 增强型---防止SQL注入攻击的方法
<?php
use SwooleCoroutine as co;
co::create(function (){
    $db = new coMySQL();
    $config=array(
        'host'=>'localhost',
        'database'=>'xxxxdb',
        'user'=>'root',
        'password'=>'xxxx',
        'fetch_mode' => true,
    );
    $db->connect($config);
    $stmt = $db->prepare("select * from colname");
    $stmt->execute();
    $res=$stmt->fetchAll();
    var_dump($res);
});
  • 增强型---带参数的查询样例
<?php
use SwooleCoroutine as co;
co::create(function (){
    $db = new coMySQL();
    $config=array(
        'host'=>'localhost',
        'user'=>'root',
        'database'=>'xxxxdb',
        'password'=>'xxxx',
        'fetch_mode'=>true,
    );
    $db->connect($config);
    $stmt = $db->prepare('select * from colname where tblbelongs=? and bz=?');
    var_dump($stmt);
    $stmt->execute(array('incomedoc_mx','s'));
    var_dump($stmt->fetchAll());
});
  •  插入语句---普通版本
<?php

go(function (){
    $swoole_mysql = new SwooleCoroutineMySQL();
    $swoole_mysql->connect([
        'host' => '127.0.0.1',
        'port' => 3306,
        'user' => 'root',
        'password' => 'xxxx',
        'database' => 'xxxxdb',
    ]);
    $swoole_mysql->begin();
    $swoole_mysql->query("insert into testpic set topic=1 ");
    $swoole_mysql->commit();
});
  • 插入语句---带预先处理
<?php
use SwooleCoroutine as co;

go(function (){
    co::create(function() {
        $db = new coMySQL();
        $server = array(
            'host' => '127.0.0.1',
            'user' => 'root',
            'password' => 'xxxx',
            'database' => 'xxxdb',
        );

        $ret1 = $db->connect($server);
        $stmt = $db->prepare('insert into testpic set topic=?, recdate=?');
        if ($stmt == false)
        {
            var_dump($db->errno, $db->error);
        }
        else
        {
            $ret2 = $stmt->execute(array('cpc and cj will marry me','2019-10-08'));
            var_dump($ret2);
        }
    });

});