473,320 Members | 1,817 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ


Query MySQL with Perl

By Blair Ireland
Senior Editor, TheScripts.com

MySQL Queries

PHP has:
mysql_query("MySQL Query", $link_id);

Perl has:
$query = $db->query($sql_query);

Just a note, the variable $sql_query is a string, and contains your SQL syntax for your query. There is no semi-colon at the end of the query in this case though. You can directly insert the string if you like as well, instead of using $sql_query.

The variable $query now contains the identifier for the query, and will be used from now on for accessing that query's data.

Gathering Data From Queries

PHP has:
mysql_fetch_row($query_id);

Perl has:
@array = $query->fetchrow;

fetchrow() returns a single row of data from your query into the array @array, starting at an offset of 0 of course. Calling fetchrow again would return the values of the next row, and so on.

PHP has:
mysql_fetch_array($query_id);

Perl has:
%hash = $query->fetchhash;

This function will return all of the column values into the hash %hash, with the column name the key, and the value as the column value. Makes sense doesn't it :-). It is very similar to fetchrow, but I usually use this one for readability sake. One drawback though is that if you have more then one column name the same, one of them will be trashed. You should use fetchrow if this is the case.

PHP has:
mysql_data_seek($query_id, $row_number);

Perl has:
$query->dataseek($row_number);

What does it do? This function will let you specify the offset for the data associated with $query. Doing another fetchrow or fetchhash will return the values of the appropriate row. Note: The first row would have an offset of 0.

Query Statement Statistics

PHP has:
mysql_num_rows($query_id);

Perl has:
$number = $query->numrows;

This function will return the number of rows returned with your query statement.

PHP has:
mysql_num_fields($query_id);

Perl has:
$number = $query->numfields;

This function will return to your scalar variable $number the amount of fields returned with your query statement.

PHP has:
mysql_affected_rows($query_id);

Perl has:
$number = $query->affectedrows

This function, as you might guess, returns the number of rows in the database affected by query.

PHP has:
mysql_insert_id($query_id);

Perl has:
$id = $query->insertid

If you have a field that is auto incremented, then this function will come in handy. It will return to you the the unique id given to the field after the query.

« Database Interaction MySQL Functions »

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.