1 <?php 2 class Sites{ 3 var $name; 4 var $url; 5 // 成员函数 6 function putname($pname){ 7 $this ->name = $pname; 8 } 9 function getname(){ 10 echo $this->name.'<br>'; 11 } 12 function puturl($purl){ 13 $this->url = $purl; 14 15 } 16 function geturl(){ 17 echo $this->url. '<br>'; 18 19 } 20 } 21 22 // 对象实例化 23 24 $baidu = new Sites; 25 $taobao = new Sites; 26 $sougou = new Sites; 27 28 29 // 调用成员函数 30 $baidu ->putname("Baidu"); 31 $taobao->putname('Tbao'); 32 $sougou->putname('Sougou'); 33 34 $baidu ->puturl('Baidu.com'); 35 $taobao->puturl('Tbao.com'); 36 $sougou->puturl("Sougou.com"); 37 38 $baidu ->getname(); 39 $taobao->getname(); 40 $sougou->getname(); 41 42 $baidu ->geturl(); 43 $taobao->geturl(); 44 $sougou->geturl(); 45 46
通过PHP操作MYSQL数据库之面向对象
php+mysqli事务控制实现银行转账 ,事务控制,也就是说所有的语句执行成功后,才会提交。否则,如果前面有语句执行成功,而后面没有执行成功,则回滚到执行之前的状态。
1 <?php 2 //1、创建数据库连接对象 3 $mysqli = new MySQLi("localhost","root","123456","liuyan"); 4 if($mysqli->connect_error){ 5 die($mysqli->connect_error); 6 } 7 $mysqli->query("set names 'GBK'"); 8 //输出查询结果 9 //$query = "select * from orders order by id desc"; 10 //$result = $db->query($query); 11 //while($res = $result->fetch_object()){ 12 // echo '<pre>'; 13 // print_r($res); 14 //} 15 //$db->query("alter table orders change ordertime time date");//更改某个字段名 16 //$db->query("delete from orders where id=5");//删除某条记录
17 18 $mysqli->autocommit(false);//首先设置autocommit为false,也就是不自动提交 20 21 $sql1 = "update account set balance=balance-2 where id=1;"; 22 $sql2 = "update account set balance=balance+2 where id=2;"; 23 $res1 =$mysqli->query($sql1) or die($mysqli->error); 24 $res2 =$mysqli->query($sql2) or die($mysqli->error); 25 26 if(!$res1 || !$res2){ 27 echo "转账失败"; 28 $mysqli->rollback();//如果有一条不成功,则回滚 29 }else{ 30 $mysqli->commit();//两条语句都执行成功,则提交 31 echo "转账成功"; 32 } 33 ?>