Turn into function

Asked

Viewed 41 times

2

I have this code that brings the user data in my database:

$resultado = mysqli_query($conexao, "select * from usuarios where id= {$id}");
$dado = mysqli_fetch_assoc($resultado);

echo $dado['nome'];
echo $dado['sobrenome'];

How do I turn this section into a function?

3 answers

3

So I got it here. I did it this way:

//Função
function dadosUsuario($id, $conexao) {
    $resultado = mysqli_query($conexao, "select * from usuarios where id= {$id}");

    return mysqli_fetch_assoc($resultado);
}

and to call the function I used:

$dado = dadosUsuario($id, $conexao);

echo $dado['cidade'];
echo $dado['estado'];
  • Interestingly yours is the best answer :) Just learn to format better. Edit see the existing formatting options.

  • Thanks @Mineiro

1


Just turning your code chunk into a function:

function getUserById ($userId)
{
    $user = new User();
    $resultado = mysqli_query($conexao, "select * from usuarios where id= {$userId}");
    $dado = mysqli_fetch_assoc($resultado);

    echo $dado['nome']; 
    echo $dado['sobrenome'];
}

Or, if you want the function with feedback, to reuse the code:

function getUserById ($userId)
{
    $user = new User();
    $resultado = mysqli_query($conexao, "select * from usuarios where id= {$userId}");
    $dado = mysqli_fetch_assoc($resultado);

    return $dado;
}
//usar a informação retornada:
$user = getUserById("5001");
echo $user['id'];
echo $user['nome'];
echo $user['sobrenome'];
  • 1

    Thanks for your @Douglasoak reply, but I’m still using php procedural. I’m creating a system to really study this paradigm and then I’m going to study object orientation. For now I am separating the functions into a separate file. You would have an example just to turn these lines into a function?

  • Yes, I’ll edit the answer

1

To create a function just put everything inside a function:

function bsucarUsuarioId($id) {
$resultado = mysqli_query($conexao, "select * from usuarios where id= {$id}");
$dado = mysqli_fetch_assoc($resultado);

return echo $dado['nome'] + $dado['sobrenome'];
}

Browser other questions tagged

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