absentx
absentx

Reputation: 1427

PHP query db in switch statement

I am using a switch statement on a $_GET variable to produce the result I want on my page.

I am always questioning the best way to run queries in situations like this because I simply do not know the best practice or method. So I have some pseudo code below and I was wondering what the best method would be.

This very well could be a situation where is just doesn't matter in terms of performance, but if it does I want to make sure I do it right.

if(isset($_GET['type'])){
   $var = $_GET['type'];

  //run the query now and select everything needed from the DB for either switch case. 
  //view implications that involve pulled data
   switch($var){

   case '1':

  //Or do I run the query here, getting only what I need for this situation
  //view implications that involve pulled data
   break;

   case '2':

   //again run the query here, getting only what I need for this situation
   //view implications that involve pulled data

   break;


   }

}

Both cases share one or two similar pieces of data from the DB, but a majority of the content for each case is only needed in that situation.

Bottom line trying to perform the best and keep the code as clean and efficient as possible.

Thanks!

Upvotes: 2

Views: 3022

Answers (3)

Pastor Bones
Pastor Bones

Reputation: 7371

It's hard to tell without seeing exactly what you're wanting in terms of data from the db, but sometimes I build a sql statement using if...then or switch and then execute the completed query.

$sql = 'SELECT * FROM myTable WHERE ';
switch($_GET['type']){
  case 1:
    $sql += 'somefield="' . mysql_real_escape_string($_GET['param1']) . '"';
  break;
  default:
  break; 
}

Upvotes: 3

Tamer Shlash
Tamer Shlash

Reputation: 9523

Of course, querying inside switch statement is better than querying before it.

It will cause less memory to be used in storing the query result, and perhaps less code to be executed (for example if you are iterating the query result).

Upvotes: 1

Jon
Jon

Reputation: 437664

Of course it will be better to only query for data that is relevant to you. There's no point in tying up the database, transferring more data over the network and then doing more work in PHP to filter out those that do not interest you. So certainly you should not query for "everything".

On the other hand, there's probably no reason to switch either. There has to be a way of rewriting your query such that you can inject the value of a variable into it and, depending on that value, it will return the data you want to in either case. This of course depends also on your database schema.

No matter what you decide to do, be careful to not expose yourself to SQL injection.

Upvotes: 4

Related Questions