Personal a problem that seems very silly about the PHP connection

Asked

Viewed 40 times

-1

I’m starting basic API for personal use, but at first I’ve come across a little problem that my eyes didn’t notice the origin:

Warning: mysqli_connect() expects Parameter 1 to be string, Object Given in

Here my connection:

<?php

function BDconecta() {

    $con = mysqli_connect("localhost", "root", NULL, "emissor_nfe") or die("Sem conexão ".  mysqli_connect_error());
    mysqli_set_charset($con, "utf8");
    return $con;

}

function BDClose($con) {
    mysqli_close($con);
}
?>

And here where I call the connection to the comic that appears the error:

<?php
include_once './conexao/conn.php';
if (!isset($_GET['pg'])) {
    echo '<h2>Escolha um Emitente para Começar:</h2><br/>';
    $query = ('Select * FROM emitente');
    $lista = mysqli_connect(BDconecta(), $query) or die("Um erro na comunicao" . mysqli_connect_error());
    $achou = mysqli_num_rows($lista);
    if ($achou > 0) {
        while ($exibir = mysqli_fetch_array($lista)) {
            $id = $exibir['id'];
            $fantasi = $exibir['nome_fantasia'];

            echo '<table><tr><td>' . $id . '</td><td>' . $fantasi . '</td></tr></table>';

        }
        echo '<br/><h2><a href="?pg=incluir">CADASTRAR</a></h2>';
    }else{
        echo '<h2 style="color: red">Nenhum Emitente Cadastrado</h2>';
        echo '<br/><h2><a href="?pg=incluir">CADASTRAR NOVO</a></h2>';
    }
} else {
    $pagina = $_GET['pg'];
    switch ($pagina) {
        case 'incluir';
            include_once './privado/cad_emitente.php';
            break;
        default:
    }
}
?>

1 answer

2


That doesn’t make sense:

$lista = mysqli_connect(BDconecta(), $query) or die("erro" . mysqli_connect_error());

You probably want this:

$con = BDconecta()
$lista = mysqli_query($con, $query) or die("Um erro na comunicao" . mysqli_error($con));

Handbook:

http://php.net/manual/en/function.mysqli-connect.php

http://php.net/manual/en/mysqli.query.php

Anyway, it is usually a bad idea to use the function directly in the query, the normal would be to store somewhere, or not use function, leave the include open and use the $con directly.

Realize I needed the $con again to recover the error on the same line.

Much simpler would be the connection not having the function, and do just that:

<?php
   $con = mysqli_connect("localhost", "root", NULL, "emissor_nfe")
      or die("Sem conexão ".  mysqli_connect_error());

And in the code simply use the $con already obtained.

Browser other questions tagged

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