Question

I have this code in my class:

public function get_data(){
        $sql = "select id_especialidad, descripcion from especialidad";
        foreach($this->dbh->query($sql) as $row)
        {
                $this->rows[] = $row;
        }
        return $this->rows;
}

Now I use it from HTML file like this:

<select>
    <?php
        $datos = $db->get_data();
        for($i=0;$i<sizeof($datos);$i++)
        {
            ?>
                <option value="<?php echo $datos[$i]["id_especialidad"]?>"><?php echo $datos[$i]["descripcion"]?></option>
           <?php
        }
    ?>
</select>

Now in the browser I see the select with the rows but in the first row is says: "Notice: Undefined index: descripcion in (file_path)"

I have 9 rows in my table but when I put this "print sizeof($datos)" it shows 11 rows.

What is happening?

is there another way to show this data?

Thanks!

Was it helpful?

Solution

Since I don't know where and how you're using or re-using $this->rows[] as you haven't posted about it, I will change a bit your code:

public function get_data()
{
    $sql = "SELECT id_especialidad, 
                   descripcion 
              FROM especialidad";
    $result = array();
    foreach($this->dbh->query($sql) as $row)
    {
        $result = $row;
    }
    return $result;
}

Given $this->dbh->query is the PDO query, if you print_r the result you get from get_data it should give you something similar to:

Array(
    [0]=>Array([id_especialidad]=>1
                             [0]=>1
                   [descripcion]=>test
                             [1]=>test
              )
    [1]=>Array([id_especialidad]=>2
                             [0]=>2
                   [descripcion]=>test2
                             [1]=>test2
              )
     )

And you can easily read it like this:

<select>
<?php
$data = $db->get_data();
foreach ($data as $item)
{
?>
    <option value="<?php echo $item["id_especialidad"]; ?>"><?php echo $item["descripcion"]; ?></option>
<?php
}
?>
</select>

If you're getting more than 9 results where it should have been only 9 I can only think there might be a problem with $this->rows[] not being cleared after used or something alike.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top