PHP: Efficient handling of conditional database queries

I have several database tables where I may have to only update one particular field,  based on conditions.

Except for that,  everything else in the statement is the same.

Instead of writing a bunch of different sql statements and calling them in a switch case,  I simply assign the target field to a variable,  and concatenate it into the sql statement that I send to the database.

Here’s an example where the value stored in $conditional dictates the target field for the update query

$p = array('newvalue',$mtindex);

$conditional = 'seven';

switch($conditional) {

case 'one':

$field = 'first';

case 'two':

$field = 'second';

case 'seven':

$field = 'seventh';


die('Unknown target field!');


$sql = 'UPDATE mytable SET '.$field.' = ? WHERE mtindex = ?';

$q = $dbh->prepare($sql);


Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s