Use of PDO. First, connect to the mysql database $ dbhnewPDO (mysql: hostlocalhost; dbnametest, $ user, $ pass). If you want to connect mssql: hostlocalhost; dbnametestdb to pgsql: hos
// Connect to the mysql database first
$ Dbh = new PDO (mysql: host = localhost; dbname = test, $ user, $ pass );
// If you want to connect to mssql:
// Mssql: host = localhost; dbname = testdb
// Connect to pgsql:
// Pgsql: host = localhost port = 5432 dbname = testdb user = bruce password = mypass
// Connect to odbc (DSN)
// Odbc: testdb
// Access:
// Odbc: Driver = {Microsoft Access Driver (*. mdb)}; Dbq = C: \ db. mdb; Uid = Admin
// Oracle, sqlite, db2 ....
// Execute a query
Foreach ($ dbh-> query (SELECT * from FOO) as $ row ){
Print_r ($ row); // The result is similar to that of mysql_fetch_array. PDOStatement: setFetchMode can be adjusted.
}
// You can also:
$ Something = $ dbh-> prepare ("SELECT name, color FROM fruit ");
$ Something-> execute ();
// Read the entire record set to the array:
$ Result = $ Something-> fetchAll ();
Print_r ($ result );
// Output:
Array
(
[0] => Array
(
[NAME] => pear
[0] => pear
[COLOUR] => green
[1] => green
)
[1] => Array
(
[NAME] => watermelon
[0] => watermelon
[COLOUR] => pink
[1] => pink
)
)
// Insert/delete/update data:
$ Count = $ dbh-> exec ("delete from fruit WHERE color = red ");
// $ Count indicates the number of deleted items. Equivalent to mysql_affected_rows
// PDOStatement: rowCount is also available
// I forgot what database I used ....
If ($ db-> getAttribute (PDO: ATTR_DRIVER_NAME) = mysql ){
Echo "Running on mysql; doing something mysql specific here ";
}
// Use mysql_escape_string when inserting data?
Print "Unquoted string: $ string ";
Print "Quoted string:". $ conn-> quote ($ string )."";
// Obtain:
Unquoted string: Nice
Quoted string: Nice
// You can see that quotation marks are automatically added ....
// Note that the results in different databases are different, for example, some are>, some are>, \=> \
// No worries, fully automated.
// Even close it.
$ Conn = null;
//! You can keep the connection:
$ Dbh = new PDO (odbc: SAMPLE, db2inst1, ibmdb2,
Array (PDO_ATTR_PERSISTENT => true ));
// Isn't it easy?
Appendix: Special simple call methods:
$ Stmt = $ dbh-> prepare ("SELECT * from registry where name =? ");
If ($ stmt-> execute (array ($ _ GET [name]) {// What are you afraid? Automatic quote!
While ($ row = $ stmt-> fetch ()){
Print_r ($ row );
}
}
You can also:
$ Stmt-> bindParam (1, $ id );
$ Stmt-> bindParam (2, $ _ FILES [file] [type]);
$ Stmt-> bindParam (3, $ fp, PDO: PARAM_LOB );
Where can I find such a good function? Php5.1 and above are in extension, php5 is in pecl, php4? Don't think about it. no.
Export $ dbh = new PDO (mysql: host = localhost; dbname = test, $ user, $ pass); // If you want to connect mssql: // mssql: host = localhost; dbname = testdb // pgsql: hos...