PDO
Posted 翟喵儿
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了PDO相关的知识,希望对你有一定的参考价值。
<?php //造DSN:驱动名:dbname=数据库名;host=服务器地址 $dsn = "mysql:dbname=mydb;host=localhost"; //造PDO对象 $pdo = new PDO($dsn,"root","123"); //写SQL语句 $sql = "select * from Info"; //执行SQL语句 //$v = $pdo->query($sql); //返回的对象比较特殊,可以直接用循环遍历 /*foreach($v as $a) { echo $a[0]; }*/ //预处理,先把SQL语句放到服务器上等待我们给他指令去执行 //准备一条SQL语句 $stm = $pdo->prepare($sql); //执行准备好的SQL语句,成功返回true,失败返回false if($stm->execute()) { //1.逐行取数据 //var_dump($stm->fetch()); //2.取所有的 //var_dump($stm->fetchAll(PDO::FETCH_OBJ)); //3.取某一列 //var_dump($stm->fetchColumn(1)); //4.返回对象 //var_dump($stm->fetchObject()); } else { echo "执行失败!"; } ?>
<?php //造对象 $dsn = "mysql:dbname=mydb;host=localhost"; $pdo = new PDO($dsn,"root","123"); //写SQL语句,参数用?来代替 //$sql = "insert into Nation values(?,?)"; $sql = "insert into Nation values(:code,:name)"; //预处理 $stm = $pdo->prepare($sql); //给参数绑定值 /*$stm->bindParam(1,$code); $stm->bindParam(2,$name); $code = "p100"; $name = "回家";*/ /*$stm->bindParam("code",$code,PDO::PARAM_STR); $stm->bindParam("name",$name,PDO::PARAM_STR); $code = "p102"; $name = "回家";*/ //造数组 //$attr = array("p101","很快"); //$attr = array("code"=>"p103","name"=>"shj"); //执行 if($stm->execute($_POST)) { echo "添加成功"; } else { echo "添加失败"; } ?>
以上是关于PDO的主要内容,如果未能解决你的问题,请参考以下文章