Cep Posted January 31, 2008 Share Posted January 31, 2008 Hi, I am delving into prepared statements and in one of my class methods I need to assemble pretty much the same update statement for several fields in the same table. So I thought rather then repeat the code I will try and come up with a dynamic way to build the sql I know it works but anyone tell me if there is a better way to do this? $original will be the current object property values, $update are the validated changes from a user form. <?php $original = array("Mickey Finagan", "mickey@bloopers.co.uk", "335", "1"); $update = array("Mike Finagan", "mickey@bloopers.co.uk", "335", "2"); $result = array_diff($update, $original); print_r($result); echo "<br />"; $sql = "UPDATE mps_users SET "; $x = 0; for ($i = 0; $i <= 4; $i++) { if (array_key_exists($i, $result)) { switch ($i) { case 0: $sql .= "display_name = ?"; $x++; break; case 1: $sql .= "email = ?"; $x++; break; case 2: $sql .= "extension = ?"; $x++; break; case 3: $sql .= "usergroup = ?"; $x++; break; } } if ($x > 0) { $sql .= ", "; $x--; } } $sql .= "WHERE user_id = ?"; echo $sql; ?> Quote Link to comment Share on other sites More sharing options...
Recommended Posts
Join the conversation
You can post now and register later. If you have an account, sign in now to post with your account.