Okay, I am working on a function that inserts a row into a MySQL table. Now, I am trying to make this thing slightly intelligent. So I have a hash that looks like the following:
my %TABLES = ( # Hash identifying one database
'users' => [ # Hash keys are the database's tables
'username',
'password', # Columns of the table in an array
'first_name',
'email_address',
'rating'
]
);
Next I have a subroutine in my module that is called like the following:
$handle->insert (
-table => "users",
-primary_key => "username",
-values => {
username => "mt2k",
first_name => "Nathan",
email_address => 'email@example.net',
password => crypt("password", $salt),
rating => 10
}
);
Next comes the part I am having problems with. Here is a sample part that is close to that of my subroutine:
sub insert {
my ($self, %q) = @_;
# Set up placeholders
my $ph = join ', ', ('?') x values %{$q{'-values'}};
# Prepare the query for the database
my $sth = $self->{DB}->prepare(
"INSERT INTO $q{'-table'} VALUES($ph)"
);
# This is the line that causes problems. Read below for more.
$sth->execute(values %{$q{'-values'}});
If you didn't catch on immediately, the problem lies in the fact that I am supplying the values of the hash to execute(). This means they are not in the correct order that MySQL requires them to be in. This is where the %TABLES hash comes in. This hash contains the arrays that hold the correct order in which the values must be passed as placeholders in the execute() statement.
So what I need to do is take the values of %{$q{'-values'}} and return them sorted in the correct order as identified by %TABLES.
I hope I've been clear enough in order to recieve some answers to this question which has perplexed me. Thanks in advance!
-
Are you posting in the right place? Check out Where do I post X? to know for sure.
-
Posts may use any of the Perl Monks Approved HTML tags. Currently these include the following:
<code> <a> <b> <big>
<blockquote> <br /> <dd>
<dl> <dt> <em> <font>
<h1> <h2> <h3> <h4>
<h5> <h6> <hr /> <i>
<li> <nbsp> <ol> <p>
<small> <strike> <strong>
<sub> <sup> <table>
<td> <th> <tr> <tt>
<u> <ul>
-
Snippets of code should be wrapped in
<code> tags not
<pre> tags. In fact, <pre>
tags should generally be avoided. If they must
be used, extreme care should be
taken to ensure that their contents do not
have long lines (<70 chars), in order to prevent
horizontal scrolling (and possible janitor
intervention).
-
Want more info? How to link
or How to display code and escape characters
are good places to start.