Error connecting connection variable (PHP / MySQLi)

1

I'm finding it difficult to call a variable from an auxiliary php code, which connects to my database, on my HTML page. I researched a lot of content, but I did not find a solution to this seemingly stupid problem.

My connection is being successfully completed, I have already tested. (connection.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 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 for all code. Where to call the variable $ con, it displays the code instead of executing a given command. Remember that I save the files inside a folder, and run from the host as per the image:

    
asked by anonymous 28.11.2018 / 21:25

2 answers

0
  

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

I basically copied and pasted your code, and everything worked.

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

connection.php :     

$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>';

Output :

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 realize that I did a reorganization and, in the end, everything worked as it should. (It was easier than debugging your code that was not returning error, simply interrupting script execution.)

See:

<?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>

Output :

I've made as few changes as possible except formatting.

    
28.11.2018 / 22:10
-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>";
  }
    
28.11.2018 / 21:44