The PDO class constructor takes the following parameters of the data source name(DSN), database name, username, and password. In the example below, a MySQL database connection object($dbc) is instantiated using a localhost server. The $dbc object establishes a connection to the test database using the applicable logon credentials of $dbuser and $pwd. Here is a simple example.
<?php
$dbc = new PDO(' mysl: = localhost; dbname= test ', $dbuser, $pwd');
?>
If there are any connection problems, a PDO exception is thrown. If the exception is not caught and handled, the default action is to terminate the script and a back trace is displayed showing the database connection details including the username and password. To mitigate this security risk, it is best to handle the exception as it occurs. Depicted below is a script to handle connection errors. $dbc = new PDO(' mysl: = localhost; dbname= test ', $dbuser, $pwd');
?>
<?php
query('SELECT * FROM testCase') as $row )
{
print_r($row);
}
$dbc = 'null ';
} catch (PDOException $e)
{
echo 'Error!:' . $e->getMessage() . ;
die();
}
?>
Upon successful connection to the database, an instance of the PDO class is returned to your script. The connection remains active for the lifetime of the PDO object. To close the connection, you need to destroy the object by ensuring that all remaining references to it are deleted--you do this by assigning NULL to the variable that holds the object. If you don't do this explicitly, PHP will automatically close the connection when your script ends. query('SELECT * FROM testCase') as $row )
{
print_r($row);
}
$dbc = 'null ';
} catch (PDOException $e)
{
echo 'Error!:' . $e->getMessage() . ;
die();
}
?>
<?php
$dbc = new PDO(' mysql:=localhost; dbname = test '; $dbuser, $dbpwd);
//use the connection here
//and now close the connection
$dbc = 'null ';
?>
$dbc = new PDO(' mysql:=localhost; dbname = test '; $dbuser, $dbpwd);
//use the connection here
//and now close the connection
$dbc = 'null ';
?>
No comments:
Post a Comment