Output SQL query result to PHP array

I'm new to OOP in PHP, does this seem right?

class whatever {

    Function Maths() {
    $this->sql->query($requete);

   $i = 0;

  while($val = mysql_fetch_array($this)) { 
    $tab[i][average] = $val['average'];
    $tab[i][randomData] = $val['sum'];
    $i=$i+1;
    }
        return $tab;
}

I want to access the data contained in an array

$foo = new whatever();
$foo->Maths();
 for ($i, $i <= endOfTheArray; i++) {

    echo Maths->tab[i][average];
    echo Maths->tab[i][randomData];
 }

Thank;)

EDIT: I want to output the result of the SQL query as an array, so I can access it from outside the class

+3
source share
2 answers

In the interest of helping you, here are some changes. Please listen to this though: a lot of this might not make sense without a good background in PHP or OOP in general. You should see the @webbiedave link.

class whatever {

  static function maths() {
    $tabs = array();
    $results = $this->sql->query($requete);

    while($val = mysql_fetch_array($this)) { 
      $tabs = $val;
    }

    return $tabs;
}
  • This fixes syntax errors and logical errors (for example, creating a variable $resultsto run an SQL query).
  • maths static, whatever() .

, :

$results = whatever::maths();
foreacho ($results as $result) {
  echo $result['average'];
  echo $result['randomData'];
}
  • maths() -, ; , , .
  • for foreach.
+5

, PHP OOP:

http://www.php.net/manual/en/language.oop5.basic.php

: . - :

$tabs = array();
while($val = mysql_fetch_assoc($result)) { 
    $tabs[] = $val;
}

$foo = new whatever();
$tabs = $foo->Maths();
for ($tabs as $tab) {
    echo $tab['average'];
    echo $tab['randomData'];
}

http://www.php.net/manual/en/language.oop5.basic.php

+5

Source: https://habr.com/ru/post/1744564/


All Articles