0

I have the following code - it produces a series of queries that are sent to a database:

$a = 'q';
$aa = 1;
$r = "$a$aa";
$q = 54;

while($aa <= $q){
$query  .= "SELECT COUNT(". $r .") as Responses FROM tresults;";
$aa = $aa + 1;
$r = "$a$aa";
}

The issue I have is simple, within the database, the number is not sequential.

I have fields that go from q1 to q13 but then goes q14a, q14b, q14c, q14d and q14e and then from q15 to q54.

I've looked at continue but that's more for skipping iterations and hasn't helped me.

I'm struggling to adapt the above code to handle this non-sequential situation. Any ideas and suggestions welcomed.

Homer_J
  • 3,277
  • 12
  • 45
  • 65
  • 4
    when db fields are named\numbered like that, its usually means its designed incorrectly –  Jan 19 '15 at 23:10
  • 1
    @Dagon - couldn't agree more - however, that's what I'm having to deal with :-( – Homer_J Jan 19 '15 at 23:12
  • 2
    @Dagon on my first job I inherited a db which only meaningful column names were `id`, the others were just `a`, `b`, `c`, ... etc. The same applied for table names. It was fun. – zerkms Jan 19 '15 at 23:12
  • 1
    @zerkms well i inherited a db where every type was *text*. dates/ numbers everything ;) –  Jan 19 '15 at 23:35

2 Answers2

2

I have fields that go from q1 to q13 but then goes q14a, q14b, q14c, q14d and q14e and then from q15 to q54.

for($i=1; $i<=54; ++$i) {
  if($i != 14) {
    echo 'q' . $i . "<br>";
  }
  else {
    for($j='a'; $j<='e'; ++$j) {
      echo 'q14' . $j . "<br>";
    }
  }
}

If you don’t need to execute the statements in order of numbering, then you could also just skip one in the first loop if the counter is 14, and then have a second loop (not nested into the first one), that does the q14s afterwards.

CBroe
  • 91,630
  • 14
  • 92
  • 150
0

You could get the columns from the table and test to see if they start with q (or use a preg_match):

$result = query("DESCRIBE tresults");

while($row = fetch($result)) {
    if(strpos($row['Field'], 'q') === 0) {
        $query  .= "SELECT COUNT(". $r .") as Responses FROM tresults;";
    }
}

Or build the columns array and use it:

$columns = array('q1', 'q2', 'q54'); //etc...

foreach($columns as $r) {
    $query  .= "SELECT COUNT(". $r .") as Responses FROM tresults;";
}
AbraCadaver
  • 78,200
  • 7
  • 66
  • 87