Function to expedite select

Asked

Viewed 56 times

0

Hello

I am developing some functions to quickly insert select and avoid filling PHP code in the pages, I create a function called select_start and another function called select_terminus and when I call these two functions, between them I insert where the results of the select will be displayed, but it is not working, what may 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>

  • 1

    You can’t get the while in one role and end in the other!

  • Suggestions: to start the code, read and understand the error that is probably appearing somewhere (or on the screen or in the log) and more: check the code colorization and closing of parentheses and keys. (Why the "select_terminus" function closes keys twice?) ;)

  • What suggestion you give me, so I can just call the function on a given page and display the result while within a <span>, without having to insert the query and while in the display page, whenever I need to list the results ?

  • insert the query and while in the location that needs to list the results is correct, anything you try to do to change it will be a hack...

2 answers

0


Put everything into one function:

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 one foreach ($res AS $linha) {...} to treat each return line of your query or 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 the possibility of errors with mysqli->error

0

You are not closing the first function and ended up inserting a function inside another function and that of the syntax error. The correct one 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>

Browser other questions tagged

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