Doubt with consultation and foreach

0

I am trying to understand why a foreach is done in this example: I have a function like:

function obtenerNombreProyecto($id = null){
    include 'conexion.php';
    try{
        return $conn->query("SELECT nombre FROM proyectos WHERE id = {$id}"); 
    } catch(Exception $e) {
        echo "Error! : " . $e->getMessage();
        return false;
    }
}

and then it is painted with:

<?php
            $proyecto = obtenerNombreProyecto($id_proyecto); 
echo var_dump($proyecto); //hago un var_dump para ver que sale
            foreach($proyecto as $nombre): 
        ?>
                <span><?php echo $nombre['nombre']; ?></span>

        <?php endforeach; ?>

The table that you query has id and name only as fields. The result of the query would be a name value, is not it? Why do you need a foreach? The result of var_dump ($ project) is:

object(mysqli_result)#3 (5) { ["current_field"]=> int(0) ["field_count"]=> int(1) ["lengths"]=> NULL ["num_rows"]=> int(1) ["type"]=> int(0) }

why? Should not the result be the value of "name" as it is done in the query?

    
asked by RicardoKra 12.08.2018 в 21:48
source

1 answer

1

If you want to omit the foreach then you could do it like this:

function obtenerNombreProyecto($id = null){ 
    include 'conexion.php'; 
    try{ 
    return $conn->query("SELECT nombre FROM proyectos WHERE id = $id"); 
    //las llaves permiten inyectar el $id 
    } catch(Exception $e) { 
        echo "Error! : " . $e->getMessage(); return false; } 
    }
    //trae un objeto de tipo result
    $proyecto = obtenerNombreProyecto($id_proyecto); 
    //utilizamos mysqli_fetch_array para que devuelva un array de tipo asociativo
    $resultado = mysqli_fetch_array($proyecto);
        ?>
                        //ya podemos imprimir la casilla que quieres
            <span><?php echo $resultado['nombre']; ?></span>

I hope you serve Bro ...

    
answered by 12.08.2018 / 22:09
source