How to call a connection within a function?

Asked

Viewed 52 times

-2

<?php
define('HOST', 'localhost');
define('USER', 'root');
define('PASS', '');
define('DBNAME', 'soufood');

try {
    $conn = new PDO('mysql:host='.HOST.';dbname='.DBNAME.';',USER, PASS);
}catch(PDOException $e) {
    echo 'ERROR: ' . $e->getMessage();
}

function ExibirCarrinho(){
    $exibirCarrinho = "SELECT * FROM carrinho";
    $exibirCarrinho = $conn->prepare($exibirCarrinho);
    $exibirCarrinho->execute();
      while ($row = $exibirCarrinho->fetch(PDO::FETCH_ASSOC)) {

      }
}
?>

inserir a descrição da imagem aqui

1 answer

1


By declaring the function this way you are saying that it will receive a parameter.

Declaring the function.

function ExibirCarrinho($parametro)
{
    $exibirCarrinho = "SELECT * FROM carrinho";
    $exibirCarrinho = $parametro->prepare($exibirCarrinho);
    $exibirCarrinho->execute();
      while ($row = $exibirCarrinho->fetch(PDO::FETCH_ASSOC)) 
      {

      }
}

When calling the function, you pass your connection instance ($Conn) by parameter.

Calling the function:

ExibirCarrinho($conn);

OBS: I changed the name of your function variable to "$parameter" only for demo.

OBS 2: According to PSR-1, method and function names must have the first lower case letter. Ref: PHP-FIG

  • 1

    Caraca! Thank you very much friend.

  • It was nothing, @Kauandouglas . Augusto already told you that in the comment. Good luck !

Browser other questions tagged

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