Beefy Boxes and Bandwidth Generously Provided by pair Networks
Problems? Is your data what you think it is?

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.

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.

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

Log In?

What's my password?
Create A New User
Node Status?
node history
Node Type: note [id://302187]
and all is quiet...

How do I use this? | Other CB clients
Other Users?
Others studying the Monastery: (3)
As of 2017-02-21 11:39 GMT
Find Nodes?
    Voting Booth?
    Before electricity was invented, what was the Electric Eel called?

    Results (309 votes). Check out past polls.