PHP operation database pdo php operation database
Load database driver
Access phpinfo. php to check whether the database driver has been loaded. the following shows that the mySql database driver has not been loaded.
Find the php. ini configuration file on drive C to enable mySql driver loading. for example, remove the semicolon.
Connect to database
// Connect to the database
$ Dsn = "mysql: dbname = test; host = 127.0.0.1"; // data source name
$ User = "root"; // user name
$ Password = "715632"; // password
Try {
$ PdoConn = new PDO ($ dsn, $ user, $ password );
Echo "database connection successful ";
} Catch (PDOException $ e ){
Echo "database connection failed". $ e-> getMessage ();
Exit;
}
Database operations
// Connect to the database
$ Dsn = "mysql: dbname = test; host = 127.0.0.1"; // data source name
$ User = "root"; // user name
$ Password = "715632"; // password
Try {
$ PdoConn = new PDO ($ dsn, $ user, $ password );
Echo "database connection successful "."
";
} Catch (PDOException $ e ){
Echo "database connection failed". $ e-> getMessage ();
Exit;
}
Try {
// Insert operation
/* $ SQL = "insert into contacts (name, telno, email) values (?,?,?) ";
$ Ptmt = $ pdoConn-> prepare ($ SQL );
$ Name = "liujun ";
$ Telno = "347535420 ";
$ Email = "liujun@qq.com ";
$ Ptmt-> bindParam (1, $ name );
$ Ptmt-> bindParam (2, $ telno );
$ Ptmt-> bindParam (3, $ email );
$ Result = $ ptmt-> execute ();
Echo "affected rows:". $ result;
*/
// Query operation
$ SQL = "select * from contacts ";
$ Ptmt = $ pdoConn-> prepare ($ SQL );
$ Result = $ ptmt-> execute ();
If ($ result = 1) {// contains the result set
While ($ list = $ ptmt-> fetch ()){
Echo $ list ['name']. "-----". $ list ['telno']. "----". $ list ['email ']."
";
}
}
} Catch (pdow.ton $ e ){
Echo "database operation failed ";
Exit;
}
Instance code: xsphp/demo. php