Using links with PDO in PHP

2

I'm trying to create a PDO loop where I can choose the desired field to position it on the page. But the code I'm using is bringing all the fields in one go.

My code looks like this:

include("libraries/conn.php");
$sql = "SELECT 
   content.id_content, 
   content.img, 
   content.titulo, 
   povos.pv, 
   cat.categoria, 
   content.inicio, 
   content.fim, 
   content.content, 
   regiao.reg, 
   regiao.wmap
FROM cat 
INNER JOIN regiao 
INNER JOIN povos 
INNER JOIN content ON povos.id_povos = content.civ 
AND regiao.id_regiao = povos.regiao 
AND cat.id_cat = content.clas
ORDER BY rand()";

$result = $PDO->query( $sql );
$rows = $result->fetchAll(PDO::FETCH_ASSOC);

print_r( $rows );

The result is coming like this:

  

Array ([0] => Array ([id_content] => 31 [img] => Paleozoic.jpg [title] = > Architecture and Housing [home] => -550000000 [end] = -250000000 [content] => The Paleozoic era prevailed from 550 to 250 million years ago, during which time the land surface underwent major transformations Among them are the emergence of mountainous clusters such as the Scandinavian Alps (Europe). This geological age is also characterized by the occurrence of sedimentary and metamorphic rocks, the formation of large forests, glaciers, first insects and reptiles. [reg] => World [wmap] => world.jpg)

    
asked by anonymous 19.07.2018 / 16:29

2 answers

1

Note that the $rows array has a 0 key with the value being another array:

Array ( [0] => 
    Array ( 
        [id_content] => 31 
        [img] => paleozoica.jpg 
        [titulo] => Era Paleozoica 
        [pv] => Indefinido 
        ...

Then to filter the result, for each key, you have an array with the data, that is, we have a loop foreach() ai, for every $rows let's separate your key and array with the values you need :

foreach ($rows as $key => $eachRow) {
    echo $eachRow['id_content'];
    echo "<br>";
    echo $eachRow['img'];
    echo "<br>";
    echo $eachRow['titulo'];
}

Because you used the FETCH_ASSOC constant to get the results, the array $rows has as its contents another array, such as $eachRow['id_content'] , $eachRow['img'] , etc, but if% the FETCH_OBJ array would have an object as content, and could be expressed inside the $rows loop like foreach() , $eachRow->id_content , etc.

    
19.07.2018 / 17:14
1

To access some information within the $rows variable, do this:

$rows->titulo
$rows->categoria
$rows->inicio
$rows->fim
...

This way you can access the records within the array and position them wherever you would like on any part of the page, as long as they are within the loop.

    
19.07.2018 / 16:36