Workerman MySQL组件Connection用法总结

Posted phperlinxinlan

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Workerman MySQL组件Connection用法总结相关的知识,希望对你有一定的参考价值。

一、初始化连接

$db = new \Workerman\mysql\Connection(‘host‘, ‘port‘, ‘user‘, ‘password‘, ‘db_name‘);

二、获取所有数据

$db->select(‘ID,Sex‘)->from(‘Persons‘)->where(‘sex= :sex AND ID = :id‘)->bindValues(array(‘sex‘=>‘M‘, ‘id‘ => 1))->query();
//等价于
$db->select(‘ID,Sex‘)->from(‘Persons‘)->where("sex= ‘M‘ AND ID = 1")->query();
//等价于
$db->query("SELECT ID,Sex FROM `Persons` WHERE sex=‘M‘ AND ID = 1");

三、获取一行数据

$db->select(‘ID,Sex‘)->from(‘Persons‘)->where(‘sex= :sex‘)->bindValues(array(‘sex‘=>‘M‘))->row();
//等价于
$db->select(‘ID,Sex‘)->from(‘Persons‘)->where("sex= ‘M‘ ")->row();
//等价于
$db->row("SELECT ID,Sex FROM `Persons` WHERE sex=‘M‘");

四、获取一列数据

$db->select(‘ID‘)->from(‘Persons‘)->where(‘sex= :sex‘)->bindValues(array(‘sex‘=>‘M‘))->column();
//等价于
$db->select(‘ID‘)->from(‘Persons‘)->where("sex= ‘F‘ ")->column();
//等价于
$db->column("SELECT `ID` FROM `Persons` WHERE sex=‘M‘");

五、获取单个值

$db->select(‘ID‘)->from(‘Persons‘)->where(‘sex= :sex‘)->bindValues(array(‘sex‘=>‘M‘))->single();
//等价于
$db->select(‘ID‘)->from(‘Persons‘)->where("sex= ‘F‘ ")->single();
//等价于
$db->single("SELECT ID FROM `Persons` WHERE sex=‘M‘");

六、复杂查询

$db->select(‘*‘)->from(‘table1‘)->innerJoin(‘table2‘,‘table1.uid = table2.uid‘)->where(‘age > :age‘)->groupBy(array(‘aid‘))->having(‘foo="foo"‘)->orderByASC/*orderByDESC*/(array(‘did‘))
->limit(10)->offset(20)->bindValues(array(‘age‘ => 13));
// 等价于
$db->query(‘SELECT * FROM `table1` INNER JOIN `table2` ON `table1`.`uid` = `table2`.`uid`
WHERE age > 13 GROUP BY aid HAVING foo="foo" ORDER BY did LIMIT 10 OFFSET 20‘);

七、插入数据

$insert_id = $db->insert(‘Persons‘)->cols(array(
    ‘Firstname‘=>‘abc‘,
    ‘Lastname‘=>‘efg‘,
    ‘Sex‘=>‘M‘,
    ‘Age‘=>13))->query();
等价于
$insert_id = $db->query("INSERT INTO `Persons` ( `Firstname`,`Lastname`,`Sex`,`Age`)
VALUES ( ‘abc‘, ‘efg‘, ‘M‘, 13)");

八、更新数据

$row_count = $db->update(‘Persons‘)->cols(array(‘sex‘))->where(‘ID=1‘)
->bindValue(‘sex‘, ‘F‘)->query();
// 等价于
$row_count = $db->update(‘Persons‘)->cols(array(‘sex‘=>‘F‘))->where(‘ID=1‘)->query();
// 等价于
$row_count = $db->query("UPDATE `Persons` SET `sex` = ‘F‘ WHERE ID=1");

九、删除数据

$row_count = $db->delete(‘Persons‘)->where(‘ID=9‘)->query();
// 等价于
$row_count = $db->query("DELETE FROM `Persons` WHERE ID=9");

十、事务处理

$db->beginTrans();
....
$db->commitTrans(); // or $db->rollBackTrans();

 

以上是关于Workerman MySQL组件Connection用法总结的主要内容,如果未能解决你的问题,请参考以下文章

swoole和workerman哪个更易开发

workerman-chat 能实现与客户端软件之间的对话么

Thinkphp6+Workerman消息推送

workerman 一个高性能的PHP Socket 服务器

使用Gateway-Worker实现多人分组实时聊天 结合第三方tp

php workerman怎么用