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", "[email protected]", "335", "1"); $update = array("Mike Finagan", "[email protected]", "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; ?> Link to comment https://forums.phpfreaks.com/topic/88709-creating-a-dynamic-prepared-statement-just-need-a-checkover-really/ Share on other sites More sharing options...
Recommended Posts
Archived
This topic is now archived and is closed to further replies.