Error when associating connection variable (PHP/Mysqli)

Asked

Viewed 233 times

1

I’m finding it difficult to call a variable from an auxiliary php code, which connects to my database, in my HTML page. I searched in several contents, but I did not find solution to this problem, apparently beast.

My connection is being carried out successfully, I have already performed tests. (conexao.php) :

<?php

$host="localhost";
$user="root";
$password="";
$dbname="database";

$con = new mysqli($host, $user, $password, $dbname);

if ($con->connect_error) 
    die("Connection failed: " . $con->connect_error);
  ?>

But when I include it in the main file (include), when calling the $con variable, the HTML page does not return correctly:

<?php
include('conexao.php');
$query = "select `id`, `nome`, `sexo` from `pessoas`"; ?>

<!DOCTYPE html>
<html>
    <meta charset = "utf8">
    <head>
        <title> Empresa </title>
    </head>
    <body>
        <header>
        <h1> Empresa </h1>
    </header>
    <?php

    if($stmt = $con -> prepare($query)) {
        $stmt -> execute();
        $stmt -> bind_result($id, $nome, $sexo); 
    ?>

        <table border = "1">
            <tr>
                <td>Id</td>
                <td>Nome</td>
                <td>Sexo</td>
            </tr>
            <?php
            while($stmt -> fetch()) { ?>
                <tr>
                    <td><?php printf("%s", $id) ?></td>
                    <td><?php printf("%s", $nome) ?></td>
                    <td><?php printf("%s", $sexo) ?></td>
                </tr>
            <?php
            } ?>
        </table>

        <?php
            $con -> close();
            } 
            else 
                echo "Erro ao executar a consulta no banco de dados."; 
        ?>
</body>

The error persists throughout the code. Where to call the $con variable, it displays the code instead of executing a given command. Remembering that save the files inside a folder, and run from the host as image :

inserir a descrição da imagem aqui

  • I copied your code to my environment, edited the db data and everything worked "as it should"... No errors... Of course it appeared to msg "Connected successfullyConnected successfully", since the connection was tested twice...

  • @bfavaretto yes, I understand that does not make sense, I put more as a test. And about the position on an html header, I will agree, but I did not succeed. I will be exposing the full code.

2 answers

0


I’m finding it difficult to call a variable from an auxiliary php code, which connects to my database, in my HTML page

I basically copied and pasted your code, and it all worked.

Soon after, I gave a small implemented in your code (comments in the files). See:

php connection.:

$host       = "--";
$user       = "--";
$password   = "--";
$dbname     = "--";

$con = new mysqli($host, $user, $password, $dbname);

if ($con->connect_error) {
    die("Falha ao conectar-se ao banco de dados: " . $con->connect_error);
} // else desnecessário: se não avisar erro, tudo está funcionando...

index php.:

<?php

include 'conexao.php';

/*
* CÓDIGO DESNECESSÁRIO, JÁ QUE A CONEXÃO É TESTADA DIRETO NO ARQUIVO "conexao.php"
*
if ($con->connect_error) {
    die("Connection failed: " . $con->connect_error);
} else echo "Connected successfully"; */

// testando a conexão "novamente"
echo '<pre>';
print_r($con);
echo '</pre>';

Exit:

mysqli Object
(
    [affected_rows] => 0
    [client_info] => mysqlnd 5.0.12-dev - 20150407 - $Id: b396954eeb2d1d9ed7902b8bae237b287f21ad9e $
    [client_version] => 50012
    [connect_errno] => 0
    [connect_error] => 
    [errno] => 0
    [error] => 
    [error_list] => Array
        (
        )

    [field_count] => 0
    [host_info] => localhost via TCP/IP
    [info] => 
    [insert_id] => 0
    [server_info] => 5.6.35
    [server_version] => 50635
    [stat] => Uptime: 4457  Threads: 2  Questions: 60  Slow queries: 0  Opens: 74  Flush tables: 1  Open tables: 3  Queries per second avg: 0.013
    [sqlstate] => 00000
    [protocol_version] => 10
    [thread_id] => 22
    [warning_count] => 0
)

@Edit:

With your complete code, I re-wrote based on yours. You will notice that I did a reorganization and, in the end, everything worked out as due. (It was easier than debugging your code that was not returning error, simply interrupted the execution of the script).

Behold:

<?php
    include('conexao.php');
    $query = "select `id`, `nome`, `cpf` from `funcionarios`";  // CONFORME A TABELA QUE USEI PARA TESTE
?>
<!DOCTYPE html>
<html>
    <meta charset = "utf8">
    <head>
        <title> Empresa </title>
    </head>
    <body>
        <header>
            <h1> Empresa </h1>
        </header>
        <?php
        if($stmt = $con -> prepare($query)) {
            $stmt -> execute();
            $stmt -> bind_result($id, $nome, $cpf); ?>
            <table border = "1">
                <tr>
                    <td>Id</td>
                    <td>Nome</td>
                    <td>CPF</td>
                </tr>
                <?php
                while($stmt -> fetch()) { ?>
                    <tr>
                        <td><?php printf("%s", $id) ?></td>
                        <td><?php printf("%s", $nome) ?></td>
                        <td><?php printf("%s", $cpf) ?></td>
                    </tr>
                <?php
                } ?>
            </table>
            <?php
            $con -> close();
        } else echo "Erro ao executar a consulta no banco de dados."; ?>
    </body>
</html>

Exit:

by LipESprY

I made as few changes as possible, save the formatting.

  • Where are you saving the . php and . html ? files, both in the same folder ? And do you use some web development environment to work these files ? I’m using wamp. In my case, except in the /www folder, according to studies conducted.

  • So there is something wrong with your code yes. But I thought it best to rewrite (little code) and test. The files are at the root of the document. Side-by-side.

  • I don’t think the problem is in the code because I copied yours and only modified the data. I only encounter problems when I split the connection (connected.php) of the main file (index.html). If you open everything in a company.php, it works normal.

  • Did you say index.html? It won’t even run! The extension should be . php! Otherwise the code will be interpreted as pure HTML... Haha

  • I knew it was not something very complex !! Now, when I would use an index.html ?

  • html is not interpreted by php! Then anything between php tags (<?php ?>) will be treated as common text.

  • This is not universal truth: "You said index.html? It won’t run anyway! The extension should be . php" - depends only on how the page server was configured. Any extension can be interpreted by PHP, and no extension either. By the way. very useful to avoid certain gambiarras with .htaccess - On a well-configured server, if you let files without extension go through PHP you can do something like a PHP named root blog be accessed like this: www.site.com/blog/bem-vindo - the file will be executed blog, and the /welcome will be a $_SERVER variable, allowing pure PHP routes

  • @Sure. But I didn’t want to implant a doubt, which doesn’t directly refer to the question, in the question’s friend’s head. Just look at the problem and it is already clear that he is a beginner. The use of other extensions is so low q, I believe, does not deserve a great explanation. There is a hint for next question! Hehe

  • 1

    @Lipespry yes, I find your comment valid in context. I just wanted to make it clear that it is not "mandatory" to open the head of future readers too (or the author of the question when it advances).

Show 4 more comments

-3

I do different try this way:

  $db = "nomdedodb";
  $servername = "localhost";
  $username = "usuario";
  $password = "senha";
  $con = mysqli_connect($servername, $username, $password, $db);
  $sql="sua query aqui por ex show tables";
  $query=mysqli_query($con,$sql);
  while($result=mysqli_fetch_array($query,MYSQLI_ASSOC)){
     echo "<pre>";
     print_r($result);
     echo "</pre>";
  }
  • The problem I’m encountering is not the database connection itself, but the moment I call variables from another php code.

Browser other questions tagged

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