Database Reference
In-Depth Information
Connecting to MySQL with DBI
After defining our parameters for Perl and the webpage, we can now connect to the data-
base, which we do with the following:
DBI->connect('DBI:mysqlPP:mysqlfast:host=localhost',phpuser,abominable);
This function connects to the database, using the mysqlPP driver in the DBI. You will
notice that the first string within the query contains the host details of where the MySQL
server is. The second and third values in the function are the username and password of the
MySQL account that we used in our PHP test earlier. The whole command above will return
a database handle to the connected data source if successful, and this needs to be stored for
later use, so we cannot just issue the code above on its own. Instead we insert the output
into a variable as follows:
my $dbh =DBI->connect(
'DBI:mysqlPP:mysqlfast:host=localhost', phpuser, abominable );
Before we use a variable in Perl we usually should define it with the my command as fol-
lows:
my $myvariable;
We can then assign a value to this variable as required. However, we can cut corners a lit-
tle by defining it at the same time as assigning the value by following the my statement with
equals and providing a value to assign as above.
Generating the Query
Finally, we are at the point where we can use a query. As we have used simple queries with
previous systems, our final example will complicate matters slightly with a join query as fol-
lows:
SELECT title, datecreated, ipnumber
FROM webpage, log
WHERE log.webpageid=webpage.id
With the Perl DBI, we need to get the query ready before actually running it. We do this
as follows:
my $sth = $dbh->prepare( 'SELECT title, datecreated, ipnumber
FROM webpage, log
WHERE log.webpageid=webpage.id');
Search WWH ::




Custom Search