-1

This might be one easy question.

I have this table:

Table Image

bairro = neighborhood / preco = price

This is a reference table with prices.

I'm trying to print a table with the neighborhood and the price, but it's not happening as I'd like:

ProblematicTable

As you guys can see, each value is being printed 3 times!

The code is this:

    function getInfo()
    {
      $this->sql = "SELECT * FROM deliverypricestable";

      $this->query = $this->mysqli->query($this->sql);

      while($this->result = $this->query->fetch_assoc())
      {
        foreach ($this->result as $key)
        {
            echo "<tr><td>".$this->result["bairro"]."</td>";//neighborhood
            echo "<td>".$this->result["preco"]."</td></tr>";//price
        }
    }

I know this problem is probably related with the numbers of column on the deliverypricestable, but I'm just learning to code, and lil lost, please help me!

marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
  • You're looping twice. – noahnu Mar 28 '16 at 21:31
  • I saw this here: http://stackoverflow.com/questions/2970936/how-to-echo-out-table-rows-from-the-db-php It has 2 loops but its printing 3 times – Fernando Anael Cabral Mar 28 '16 at 21:35
  • See my answer. In the link you posted, the code is looping through the keys because it's printing the individual cell values. In your code, you're printing the entire row each iteration. You'll see what I mean if you print `$key` instead of `$this->result['...']`. – noahnu Mar 28 '16 at 21:36
  • Again, see my answer. The condition in the while loop retrieves the next row every iteration. That's not the loop you want to remove. – noahnu Mar 28 '16 at 21:39

2 Answers2

0
function getInfo()
{
$query = "SELECT * FROM deliverypricestable";

if ($result = $mysqli->query($query)) {

/* fetch associative array */
while ($row = $result->fetch_assoc()) {
    echo "<tr><td>".$query->result["bairro"]."</td>";//neighborhood
    echo "<td>".$query->result["preco"]."</td></tr>";//price);
}

/* free result set */
$result->free();
}

/* close connection */
$mysqli->close();
}

You might find - http://php.net/manual/en/mysqli.query.php - useful for documentation on what you are trying to do.

-1

There's no reason to loop twice. The while loop will execute while there is a new row. This new row is stored in $this->result.

function getInfo()
{
    $this->sql = "SELECT * FROM deliverypricestable";
    $this->query = $this->mysqli->query($this->sql);

    while($this->result = $this->query->fetch_assoc()) {
        echo "<tr><td>".$this->result["bairro"]."</td>";//neighborhood
        echo "<td>".$this->result["preco"]."</td></tr>";//price
    }
}

What your code is doing is looping through all the rows and then for each row, you're looping through all the keys (columns) belonging to the row. You have 3 columns and so for each row, you print the values 3 times.

noahnu
  • 3,479
  • 2
  • 18
  • 40