Jump to content

Creating a dynamic prepared statement - just need a checkover really :)


Cep

Recommended Posts

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;
?>

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.