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 :
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...
– LipESprY
@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.
– Paulo Bomfim