I. Connection of PDO
$host= "localhost"; $dbname= "Hejuntest"; $username= "Root"; $pwd= ""; $dsn= "mysql:host=$host;d bname=$dbname"; $opt=Array(Pdo::attr_persistent =TRUE);//Persistent Links Try{ $pdo=NewPDO ($dsn,$username,$pwd,$opt); }Catch(pdoexception$e){ Echo' Connect error~ '.$e-Get_message (); }
Second, the increase, deletion and modification of PDO
$sql = "Update student set name= ' Xiaoran ' where ID in ("); $affted _rows $pdo,exec($sql); // returns the number of rows affected
Third, the search for PDO
$sql= "SELECT * FROM Student"; $pdostatement=$pdo->query ($sql); Echo' <table> '; while(List($id,$name,$age,$class) =$pdostatement->fetch (PDO::fetch_num)) { Echo' <tr> '; Echo' <td> '.$id.‘ </td> '; Echo' <td> '.$name.‘ </td> '; Echo' <td> '.$age.‘ </td> '; Echo' <td> '.$class.‘ </td> '; Echo' </tr> '; } Echo' </table> ';
$sql= "SELECT * FROM Student"; $pdostatement=$pdo->query ($sql); $data=$pdostatement->fetchall (PDO::FETCH_ASSOC); Echo' <table> '; foreach($data as $k=$v){ Echo' <tr> '; Echo' <td> '.$v[' ID ']. ' </td> '; Echo' <td> '.$v[' name ']. ' </td> '; Echo' <td> '.$v[' Age ']. ' </td> '; Echo' <td> '.$v[' class ']. ' </td> '; Echo' </tr> '; } Echo' </table> ';
Iv. pretreatment of PDO (Pretreatment is supported)
- Specifying a moniker Binding variable
$sql= "INSERT into student (Name,age,class) VALUES (: Name,:age,:class)"; $pdostatement=$pdo->prepare ($sql); $pdostatement->bindparam (": Name",$name); $pdostatement->bindparam (": Age",$age); $pdostatement->bindparam (": Class",$class); $name= "Hejun"; $age= 25; $class= 15; $pdostatement-execute (); $name= "Daxi"; $age= 26; $class= 16; $pdostatement->execute ();
- ? Symbolic binding variables
$sql= "INSERT into student (Name,age,class) VALUES (?,?,?)"; $pdostatement=$pdo->prepare ($sql); $pdostatement->bindparam (1,$name); $pdostatement->bindparam (2,$age); $pdostatement->bindparam (3,$class); $name= "Hejun"; $age= 25; $class= 15; $pdostatement-execute (); $name= "Daxi"; $age= 26; $class= 16; $pdostatement->execute ();
- Omit bound variable method
$sql = "INSERT into student (Name,age,class) VALUES (?,?,?)" ; $pdostatement $pdo->prepare ($sql); $pdostatement->execute (array("Daxixi", 20,11)); Echo $pdo // If there is a primary key, get the last inserted primary key value Echo $pdostatement->rowcount (); // get the number of affected rows
Database Abstraction Layer PDO