Fernando Anael Cabral Fernando Anael Cabral - 3 months ago 8
PHP Question

Can't print all rows and columns from table

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!

Answer

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.

Comments