The $sth is a mutable string… Which means you can change it at runtime!
Here's an example of a modified $sth at runtime:
my $up_sql = defined($updated_at) ? 'updated_at < ? AND ' : undef;
my $sql = "SELECT * FROM mytable WHERE $up_sql type_id = ? AND serial_number
IN (
SELECT serial_number FROM anothertable WHERE device_id = ?)";
my $sth = $dbh->prepare($sql);
my $i = 1;
if (defined($up_sql)) {
$sth->bind_param($i, $updated_at, SQL_INTEGER); $i++;
}
$sth->bind_param($i, $pass_type_id, SQL_VARCHAR); $i++;
$sth->bind_param($i, $device_id, SQL_VARCHAR); $i++;
$sth->execute;
On Oct 22, 2012, at 9:16 AM, Tim Bowden <[email protected]> wrote:
> Is it possible, and if so, how can I set the number of placeholders in a
> prepared statement at runtime?
>
> IE, given something like:
>
> my $sth = $dbh->prepare("INSERT INTO $table ($fields) VALUES (?,?,?));
>
> which is fine if I know how many fields I'm inserting into, but what if
> I don't know till runtime how many fields? How can I put the (?,?,?)
> into a variable and have it recognised as placeholders?
>
> Thanks,
> Tim Bowden
>