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';
break;

case 'two':

$field = 'second';
break;

case 'seven':

$field = 'seventh';
break;

default:

die('Unknown target field!');
break;


}

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

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

Advertisements

Leave a Reply

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

WordPress.com Logo

You are commenting using your WordPress.com 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