Reading fields from a table

Asked

Viewed 41 times

1

I am reading a table that has 12 fields (campo_1, campo_2, ..., campo_12).

After each reading of a record, I need to do a repeat treatment for each column (only changes the field name). So I need to repeat the code 12 times, one for each column.

I wonder if there’s any code that makes a loop, guy FOR...NEXT or something similar, where the treatment would be written only once, varying the name of the field.

Example of how I’m doing:

$string_sql = "select * from TABELA where CHAVE = '" . $key . "'";
$query = ibase_query($connection,$string_sql);
while ($row = ibase_fetch_object($query)) {
    if ($row->CAMPO_1 <> 0) {
        .......
        .......
    }

    if ($row->CAMPO_2 <> 0) {
        .......
        .......
    }

    if ($row->CAMPO_3 <> 0) {
        .......
        .......
    }

    .......
    .......
    .......
    .......

    if ($row->CAMPO_12 <> 0) {
        .......
        .......
    }
}

What I thought:

$string_sql = "select * from TABELA where CHAVE = '" . $key . "'";
$query = ibase_query($connection,$string_sql);
while ($row = ibase_fetch_object($query)) {
    for ($x = 1 ; $x <= 12 ; $x++) {
        if ($row->CAMPO_$x <> 0) {
            .......
            .......
        }
    }
}

2 answers

1

Like $row is an object you can pick up the property with get_object_vars($row).

Take a look in the manual of get_object_vars.

Or you can recover as an array and return the keys, I think there are several solutions.

  • I got it with your suggestion. Thanks for your help.

1


As colleague Rafael said, take the properties of the object using get_object_vars, then you concatenate the $x of the loop with the name of the fields:

while ($row = mysqli_fetch_object($query)) {

   $campos = get_object_vars($row);
   for ($x = 1 ; $x <= 12 ; $x++) {
      if ($campos['campo_'.$x] <> 0) {
         // faz alguma coisa
      }
   }

}
  • Yes...I got it with the tips. Thank you.

  • Then you can mark the answer you thought best. Abs!

  • I’m a new user here. How do I mark up that you mentioned ?

  • Next to the answer is an icon to click.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.