//First connect to the mysql database
$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
//Even access:
//odbc:Driver={Microsoft Access Driver (*.mdb)};Dbq=C:\db.mdb;Uid=Admin
//There are also oracle, sqlite, db2....
//Execute a query
foreach ($dbh->query('SELECT * from FOO') as $row) {
print_r($row); //This result is similar to mysql_fetch_array. PDOStatement::setFetchMode can be adjusted.
}
//Also:
$sth = $dbh->prepare("SELECT name, color FROM fruit");
$sth->execute();
//Read the entire record set into the array:
$result = $sth->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 is the number of deleted items. Equivalent to mysql_affected_rows
//You can also use PDOStatement::rowCount
//I forgot what database I used. . . .
if ($db->getAttribute(PDO::ATTR_DRIVER_NAME) == 'mysql') {
echo "Running on mysql; doing something mysql specific heren";
}
//Mysql_escape_string used to be used when inserting data, now?
print "Unquoted string: $stringn";
print "Quoted string: " . $conn->quote($string) . "n";
//get:
Unquoted string: Nice
Quoted string: 'Nice'
//You see, even the quotation marks are automatically added now. . . .
//Note that the results are different in different databases, such as some ' => '', some ' => ', => \
//No worries now, fully automatic.
//Finally I have to close it
$conn = null;
//but! You can stay connected by:
$dbh = new PDO('odbc:SAMPLE', 'db2inst1', 'ibmdb2',
array(PDO_ATTR_PERSISTENT => true));
//Very simple, isn't it?
Attachment: A very simple special calling method:
$stmt = $dbh->prepare("SELECT * FROM REGISTRY where name = ?");
if ($stmt->execute(array($_GET['name']))) { //What are you afraid of? Automatic quote!
while ($row = $stmt->fetch()) {
print_r($row);
}
}
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 the extension, php5 is in pecl, php4? Don’t think about it, no.