<?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 "添加失敗"; } ?>