开发者

Output a result of an SQL query to a PHP array

开发者 https://www.devze.com 2022-12-29 19:34 出处:网络
I\'m new to OOP in PHP, is that to seems correct ? class whatever { Function Maths() { $this->sql->query($requete);

I'm new to OOP in PHP, is that to seems correct ?

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 the array

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

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

Thank you ;)

开发者_开发知识库

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


In the interest of helping you out, here are some modifications. Please hear this, though: a lot of this might not make sense without a good background in PHP or OOP in general. You should look at @webbiedave's link.

class whatever {

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

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

    return $tabs;
}
  1. This fixes syntax errors and logic errors (for instance, the creation of the $results variable to hold the SQL query run).
  2. I made the maths method static, since there's really no need to instantiate a whatever() object with this current example.

Here are some modifications to how this would be used:

$results = whatever::maths();
foreacho ($results as $result) {
  echo $result['average'];
  echo $result['randomData'];
}
  1. Since maths() returns something, you need to store that in a variable; simply calling it, as you did previously, doesn't do anything.
  2. That convoluted for loop can be replaced with a foreach loop.


Please check out PHP OOP basics:

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

Edit: Thanks for cleaning up the code. Try something along the lines of:

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

And:

$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

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号