Beefy Boxes and Bandwidth Generously Provided by pair Networks
P is for Practical
 
PerlMonks  

Re: How to get a placeholder to keep the current column value?

by gmax (Abbot)
on Oct 26, 2003 at 10:06 UTC ( #302187=note: print w/ replies, xml ) Need Help??


in reply to How to get a placeholder to keep the current column value?

Fetching the old values or using column names for dummy updates sounds like a waste of resources to me.

Since I guess that you can get the XML nodes into a hash, I would go for the simpler solution, using a dynamically built SQL statement.

Here is a (tested) example of creating a query with placeholders using a well established idiom. (See DBI recipes for more on this subject.)

# assume this is the hash containing translated XML nodes my %hash = ( phone => '456', street => 'Malcom St.' ); my @fields = keys %hash; my $ID = "34567"; my $update_query = qq{UPDATE address\n SET} . join(",\n", map { " $_ = ? "} @fields) . qq{\nWHERE id = ?}; print "$update_query\n"; my $sth = $dbh->prepare($update_query); my $rows = $sth->execute(@hash{@fields}, $ID); print "$rows rows affected\n"; __END__ The query produced by this code is UPDATE address SET phone = ? , street = ? WHERE id = ?

Provided that the keys in your hash have a corresponding column name, you can add or remove keys at will, and this kind of code will work smoothly.

Update
Be aware that this solution won't work when the value submitted for update is a formula. E.g. UPDATE wages SET salary = salary * 1.25 . If you pass "salary * 1.25" to a placeholder, you'll get a string, which MySQL tries to convert into a number, thus resulting in a value of "0" (zero). See the MySQL manual.
Remember that, since placeholders imply quoting, if you want to allow your users to use formulas you'll need to parse their input, check for allowed expressions, quote the quotable parts, and compose the query in a different way.

 _  _ _  _  
(_|| | |(_|><
 _|   


Comment on Re: How to get a placeholder to keep the current column value?
Select or Download Code

Log In?
Username:
Password:

What's my password?
Create A New User
Node Status?
node history
Node Type: note [id://302187]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this? | Other CB clients
Other Users?
Others contemplating the Monastery: (8)
As of 2014-12-25 03:27 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    Is guessing a good strategy for surviving in the IT business?





    Results (159 votes), past polls