您好,欢迎访问一九零五行业门户网

php mysql连接方式pdo用法详解

setattribute(pdo::attr_errmode, pdo::errmode_exception); $dbh->exec('set names utf8'); /*添加*///$sql = insert into `user` set `login`=:login and `password`=:password; $sql = insert into `user` (`login` ,`password`)values (:login, :password); $stmt = $dbh->prepare($sql); $stmt->execute(array(':login'=>'kevin2',':password'=>'')); echo $dbh->lastinsertid(); /*修改*/$sql = update `user` set `password`=:password where `user_id`=:userid; $stmt = $dbh->prepare($sql); $stmt->execute(array(':userid'=>'7', ':password'=>'4607e782c4d86fd5364d7e4508bb10d9')); echo $stmt->rowcount(); /*删除*/$sql = delete from `user` where `login` like 'kevin_'; //kevin% $stmt = $dbh->prepare($sql); $stmt->execute(); echo $stmt->rowcount(); /*查询*/$login = 'kevin%'; $sql = select * from `user` where `login` like :login; $stmt = $dbh->prepare($sql); $stmt->execute(array(':login'=>$login)); while($row = $stmt->fetch(pdo::fetch_assoc)){ print_r($row); } print_r( $stmt->fetchall(pdo::fetch_assoc)); ?>
复制代码
1、建立连接
true )); ?>
复制代码
持久性链接pdo::attr_persistent=>true
2,捕捉错误
setattribute(pdo::attr_errmode,pdo::errmode_exception); $dbh->exec(set character set utf8); $dbh=null; //断开连接 }catch(pdoexception$e){ printerror!:.$e->getmessage().
; die(); }?>
复制代码
3,pdo事务
setattribute(pdo::attr_errmode,pdo::errmode_exception);$dbh->begintransaction();//开启事务$dbh->exec(insertintostaff(id,first,last)values(23,'joe','bloggs'));$dbh->exec(insertintosalarychange(id,amount,changedate)values(23,50000,now()));$dbh->commit();//提交事务}catch(exception$e){$dbh->rollback();//错误回滚echofailed:.$e->getmessage();}?>
复制代码
4. 错误处理a. 静默模式(默认模式)
setattribute(pdo::attr_errmode, pdo::errmode_warning); $stmt = $dbh->prepare($sql); $stmt->bindparam(':country', $country, pdo::param_str); $stmt->execute(); while ($row = $stmt->fetch(pdo::fetch_assoc)) { print $row['name'] . /t; } } // if there is a problem we can handle it here catch (pdoexception $e) { echo 'pdo exception caught. '; echo 'error with the database:
'; echo 'sql query: ', $sql; echo 'error: ' . $e->getmessage(); } ?>
复制代码
1,使用 query()
query($sql); 当$sql 中变量可以用$dbh->quote($params); //转义字符串的数据$sql = 'select * from city where countrycode ='.$dbh->quote($country); foreach ($dbh->query($sql) as $row) { print $row['name'] . /t; print $row['countrycode'] . /t; print $row['population'] . /n; } ?>
复制代码
2,使用 prepare, bindparam和 execute [建议用,同时可以用添加、修改、删除]
prepare($sql); 产生了个pdostatement对象pdostatement->bindparam()pdostatement->execute();//可以在这里放绑定的相应变量?>
复制代码
3、php pdo事务例子
query('set names utf8;'); $dbh->setattribute(pdo::attr_errmode, pdo::errmode_exception); $dbh->begintransaction(); $dbh->exec(insert into `test`.`table` (`name` ,`age`)values ('mick', 22);); $dbh->exec(insert into `test`.`table` (`name` ,`age`)values ('lily', 29);); $dbh->exec(insert into `test`.`table` (`name` ,`age`)values ('susan', 21);); $dbh->commit(); } catch (exception $e) { $dbh->rollback(); echo failed: . $e->getmessage(); } ?>
复制代码
其它类似信息

推荐信息