Function to stream select

0

Hello

I'm developing functions to speed select insert and avoid filling PHP code in the pages, I create a function called select_inicio and another function called select_termino and when I call these two functions, among them I insert where the results of the select will appear, but it is not working, what could be wrong?               

include 'include/connection.php';

function select_inicio()
{
    $query = "SELECT id, imagem, produto FROM produtos ORDER BY id ASC";

    $result = mysqli_query($link, $query) or die(mysql_error());

    while ($row = mysqli_fetch_array($result))
    {
}

function select_termino()
{
    }
}

?>
</head>
<body>
<?php select_inicio(); ?>
<?php echo $row[0]; ?>
<?php select_termino(); ?>
</body>
</html>
    
asked by anonymous 27.10.2016 / 20:51

2 answers

0

Put everything into one function only:

include 'include/connection.php';

function select($query)
{
    $result = mysqli_query($link, $query) or die(mysql_error());
    while ($row = mysqli_fetch_array($result))
    {
        $retorno[] = $row;
    }
}
?>

<body>
<?php 
    $res = select("SELECT id, imagem, produto FROM produtos ORDER BY id ASC");
    var_dump($res);
?>
</body>
</html>

Then you can use foreach ($res AS $linha) {...} to treat each line of your query's return or to access a specific line with $res[0]['campo'] . Well, it's just the principle to be used, you need to develop the code better, remember to also deal with error possibilities with mysqli->error

    
27.10.2016 / 21:34
0

You are not closing the first function and you end up inserting a function inside another function and that is the syntax error. The correct would be:

include 'include/connection.php';

function select_inicio()
{
    $query = "SELECT id, imagem, produto FROM produtos ORDER BY id ASC";

    $result = mysqli_query($link, $query) or die(mysql_error());

    while ($row = mysqli_fetch_array($result))
    {
    }

}

function select_termino()
{

}

?>
</head>
<body>
<?php select_inicio(); ?>
<?php echo $row[0]; ?>
<?php select_termino(); ?>
</body>
</html>
    
27.10.2016 / 21:41