473,405 Members | 2,445 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ


Perl and the Database

By Blair Ireland
Senior Editor, TheScripts.com

Perl MySQL Database Intro

PHP has:
mysql_list_dbs($link_id);

Which can be traversed by using this code....

$result = mysql_list_dbs($link_id);
$i = 0;
while ($i < mysql_num_rows ($result)) {
$db_names[$i] = mysql_tablename ($result, $i);
echo $db_names[$i] . "<BR>";
$i++;
}

Perl has:
@array = $db->listdbs;

Which can be traversed simply by:

foreach $database (@array) {
print $database."\n<BR>";
}

A lot simpler looking? Yes, a very good thing. This function will simply return all of the databases found in the current MySQL daemon into the array @array.

PHP has:
mysql_list_tables("database name", $link_id);

Which, again, can be traversed using

$result = mysql_list_tables("database name", $link_id);
$i = 0;
while ($i < mysql_num_rows ($result)) {
$tb_names[$i] = mysql_tablename ($result, $i);
echo $tb_names[$i] . "<BR>";
$i++;
}

Perl has:
@array = $db->listtables;

Which, just like the listdbs function, can be traversed simply by:

foreach $table (@array) {
print $table."\n<BR>";
}

The listtables function already has the database selected, by using selectdb() above, so you do not have to specify the database again. All of the tables found in the database are returned to the @array variable in this example.

PHP has:
mysql_list_fields("database name", "table name", $link_id);

Information about the given tablename is returned.The pointer returned can be used with mysql_field_flags(), mysql_field_len(), mysql_field_name(), and mysql_field_type().

Perl has:
$fields = $db->listfields($table);

Here we grab the column information about our table specified. The $fields pointer can now be used with $fields->name; for the names of the columns,

If you only want a single name though, say, for the second column, you would just have to write $second_column = $fields->name->[+0]. Why did I put in [+0]? You have to remember it's in array context, so the first column would be found in [0], second in [+0], third in [2], etc.

@array = $fields->type; for an array of the datatypes
@array = $fields->length; for the maximum lengths of all the datatypes in the table (in bytes).

Some of the extra functions include:

I think you get the idea though..... this function probably won't be used to often, but, if it is, it can be handy with this large inventory of functions.
« Perl and MySQL Query MySQL »

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.