IMPORTANT: Per accedir als fitxer de subversion: http://acacha.org/svn (sense password). Poc a poc s'aniran migrant els enllaços. Encara però funciona el subversion de la farga però no se sap fins quan... (usuari: prova i la paraula de pas 123456)

mysql_* functions

PDO

Són les inicials de PHP Data Objects.

Interessant screencast:

https://laracasts.com/series/php-for-beginners/episodes/13

Exemple 1. Connectar a un servidor MySQL

Abans:

<?php
$link = mysql_connect('localhost', 'user', 'pass');
mysql_select_db('testdb', $link);
mysql_set_charset('UTF-8', $link);

PDO utilitza DSN un string d'opcions per indicar el driver a utilitzar i els detalsl de la connexió. Més info a:

http://www.php.net/manual/en/ref.pdo-mysql.connection.php
<?php
$db = new PDO('mysql:host=localhost;dbname=testdb;charset=utf8', 'username', 'password');

Ex poden passar paràmetres. Exemple

<?php
$db = new PDO('mysql:host=localhost;dbname=testdb;charset=utf8', 'username', 'password', array(PDO::ATTR_EMULATE_PREPARES => false, 
                                                                                             PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION));

o:

<?php
$db = new PDO('mysql:host=localhost;dbname=testdb;charset=utf8', 'username', 'password');
$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$db->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);

Exemple 2. Control d'errors

Abans:

<?php
//connected to mysql
$result = mysql_query("SELECT * FROM table", $link) or die(mysql_error($link));

OR die no és la millor opció per a controlar errors.

PDO té tre modes:

  1. PDO::ERRMODE_SILENT acts like mysql_* where you must check each result and then look at $db->errorInfo(); to get the error details.
  2. PDO::ERRMODE_WARNING throws PHP Warnings
  3. PDO::ERRMODE_EXCEPTION throws PDOException. In my opinion this is the mode you should use. It acts very much like or die(mysql_error()); when it isn't caught, but unlike or die() the PDOException can be caught and handled gracefully if you choose to do so.
<?php
try {
    //connect as appropriate as above
    $db->query('hi'); //invalid query!
} catch(PDOException $ex) {
    echo "An Error occured!"; //user friendly message
    some_logging_function($ex->getMessage());
} 

NOTA: you do not have to handle with try catch right away. You can catch it anytime that is appropriate. It may make more sense to catch it at a higher level like outside of the function that calls the PDO stuff:

<?php
function getData($db) {
   $stmt = $db->query("SELECT * FROM table");
   return $stmt->fetchAll(PDO::FETCH_ASSOC);
}

//then much later
try {
   getData($db);
} catch(PDOException $ex) {
   //handle me.
}

Exemple 3 Exemples de Select

Consider the mysql_* code:

<?php
$result = mysql_query('SELECT * from table') or die(mysql_error());

$num_rows = mysql_num_rows($result);

while($row = mysql_fetch_assoc($result)) {
   echo $row['field1'].' '.$row['field2']; //etc...
}

In PDO You can run such queries like this:

<?php
foreach($db->query('SELECT * FROM table') as $row) {
    echo $row['field1'].' '.$row['field2']; //etc...
}

query() method returns a PDOStatement object. You can also fetch results this way:

<?php
$stmt = $db->query('SELECT * FROM table');

while($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
    echo $row['field1'].' '.$row['field2']; //etc...
}

or

<?php
$stmt = $db->query('SELECT * FROM table');
$results = $stmt->fetchAll(PDO::FETCH_ASSOC);
//use $results

Vegeu també

Enllaços externs