How to use a fetch_array contained in another PHP page?

Asked

Viewed 52 times

0

Example: SELECTS Has three names, I want to print these 3 names on another page.

page1.php

<?php
session_start();
include_once("config.php");
?>

<?php 
$sql = $db->query("SELECT nome FROM banco_de_dados");//SELECT TEM 3 nomes (vitor,matheus,carol)
?>

<?php
    while($dados = $sql->fetch_array()){
    $nome = $dados['nome'];

    $_SESSION['nome'] = $nome;
    };

?>

page2.php

<?php
session_start();
$nome = $_SESSION['nome'];
echo $nome;
?>

print on the page:

vitor
matheus
carol
  • https://i.stack.Imgur.com/evLUR.png

  • https://pt.meta.stackoverflow.com/questions/1078/como-e-por-que-aceitar-uma-resposta/1079#1079

3 answers

0

Your question is a little confused, but I think I get it. In this case you are only printing a name because the name is being overwritten on $_SESSION (I’ve had this problem on my TCC). What can be done to solve this problem is instead of using $_SESSION you can call the page straight, so:

<?php
session_start();
include_once("config.php");

$sql = $db->query("SELECT nome FROM banco_de_dados");//SELECT TEM 3 nomes (vitor,matheus,carol)

while($dados = $sql->fetch_array()){
echo $dados['nome'];
}

Already on the page where it will be shown:

<?php
session_start();
require_once 'pagina1.php';

So it will run page 1 on page 2, showing the data inside page 2.

0

Do it like this:

$num = 0;
while($dados = $sql->fetch_array()){
$nome = $dados['nome'];
$_SESSION['nome_id'.$num] = $nome;
$num++;
}

already on page 2 you put the sequence:

echo $_SESSION["nome_id1"];
echo $_SESSION["nome_id2"];
echo $_SESSION["nome_id3"];

Or do as the member of the first response.

  • 1

    Amigo Léo, Your information helped me 50%. I will try to rephrase my question to see if there is possibility of you helping me. Thanks for your help.

0


page1.php

while($dados = $sql->fetch_array()){
//concatena os nomes separando-os por virgula
$nomes .= $dados['nome'].",";
};

//retira a ultima virgula
$nomes=substr($nomes, 0, -1);
$_SESSION['nome'] = $nomes; / vitor,matheus,carol

page2.php

If you just print each name on a line, replace it with a comma for a line break

session_start();
$nome = $_SESSION['nome'];

echo str_replace(',','<br>',$nome);

or

session_start();

$nomes = explode(',',$_SESSION['nome']);

echo $nomes[0];
echo "<br>";
echo $nomes[1];
echo "<br>";
echo $nomes[2];
  • Poxa cara helped me a lot. Very much. Vlw

Browser other questions tagged

You are not signed in. Login or sign up in order to post.