Perl script or MySQL fix?
I am new to Perl and just got an assignment with perl scipt. The statement I'm currently focusing on is:
my $sth = $dbh->prepare('SELECT StringValue FROM CustomData WHERE (Record_ID = \'' . $ref->{'Record_ID'} . '\' && Field_ID = \'' . $metadata[11] . '\') LIMIT 1;');
The current instruction will pull each entry that matches the value Record_ID
. However, it needs to be changed to , only pull records where the Record_ID starts with the number 1,2,9 .
I think this looks more like a regex problem, is that correct? If this is the case, I should only modify
Record_ID = \'' . $ref->{'Record_ID'}
part. It's right? Or should it be something that needs to be recorded in the instructions prepare
?
source to share
You should be using placeholders instead of trying to interpolate your variables and trying to make your own quote. You might even consider using placeholders for '1%'
etc., aside from considering them static in all your queries.
my $sth = $dbh->prepare( q#
SELECT StringValue FROM CustomData
WHERE (Record_ID = ? && Field_ID = ?)
AND (Record_ID LIKE '1%' OR Record_ID LIKE '2%' OR Record_ID LIKE '9%')
LIMIT 1
#);
$sth->execute($ref->{'Record_ID'}, $metadata[11]);
source to share
You're right about changing the part Record_ID = \'' . $ref->{'Record_ID'} . '\'
replace it with Record_ID LIKE \'1%\' || Record_ID LIKE \'2%\' || Record_ID LIKE \'9%\'
Remove LIMIT 1
, this only matches one line starting at 1,2 or 9
This is how I think the solution might go
my $sth = $dbh->prepare('
SELECT StringValue
FROM CustomData
WHERE ( Record_ID LIKE \'1%\' || Record_ID LIKE \'2%\' || Record_ID LIKE \'9%\'
&& Field_ID = \''. $metadata . '\');');
$sth->execute;
while (my @arr=$sth->fetchrow_array())
{
print @arr;
}