Displaying a mysql table on the html page

Asked

Viewed 2,374 times

2

Good morning friends! Searching, I was able to join this code from the 'show test' page to expose the contents of the 'testimony' table of the BD 'beja_provida'. However, it does not give the expected result. Will someone give me a light, please? Code:

    <!DOCTYPE HTML>
<html lang="pt-BR">
 <head>
  <title>ListaTestem</title>
 </head>
<body>

<h1>Exibir dados com PHP/MySql</h1>

<?php

$servidor = "localhost"; /*maquina a qual o banco de dados está*/
$usuario = "root"; /*usuario do banco de dados MySql*/
$senha = "joanin21"; /*senha do banco de dados MySql*/
$banco = "beja_provida"; /*seleciona o banco a ser usado*/

$conexao = mysqli_connect($servidor,$usuario,$senha);  /*Conecta no bando de dados MySql*/

mysqli_select_db($banco); /*seleciona o banco a ser usado*/

$res = mysqli_query("SELECT * FROM testemunho ORDER BY nome")or die (mysqli_error($escrever); /*Executa o comando SQL, no caso para pegar todos os usuarios do sistema e retorna o valor da consulta em uma variavel ($res)  */

echo "<table><tr><td>ID</td><td>Nome</td><td>E-mail</td><td>Testemunho</td></tr>";

/*Enquanto houver dados na tabela para serem mostrados será executado tudo que esta dentro do while */
while($escrever=mysqli_fetch_array($res)){

/*Escreve cada linha da tabela*/
echo "<tr><td>" . $escrever['id_testem'] . $escrever['nome'] . "</td><td>" . $escrever['email'] . "</td><td>" . $escrever['testemunho'] . "</td></tr>";

} /*Fim do while*/

echo "</table>"; /*fecha a tabela apos termino de impressão das linhas*/

mysql_close(conexao);

?>
</body>
</html>

Upshot:

Resultado The HTML that calls the 'show test' tab is this:

<!DOCTYPE HTML>
<html lang="pt-BR">
<head>
	<meta charset="UTF-8">
	<title>Savino</title>
	<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
	<script src="provida.js"></script>
	<link href="//netdna.bootstrapcdn.com/font-awesome/3.2.1/css/font-awesome.css" rel="stylesheet">
	<link href="//netdna.bootstrapcdn.com/twitter-bootstrap/2.3.2/css/bootstrap-combined.no-icons.min.css" rel="stylesheet">
	<link rel="stylesheet" href="provida.css">
</head>
<body>
<div id="fundo-externo">
	<div id="fundo">
		<img src="imgPv/providaUfpa.png" alt="Provida" />
	</div>
</div>
<div id="site">
<h1>TESTEMUNHOS</h1></a>
<h1><strong><a href="savinoPortugues.html" alt="Apresentação" style="text-decoration:none">“ o Reino de Deus è a coordenação de todas as forças positivas que existem no mundo a fim de que consigam transformar a vida numa nova e apreciável realidade sem dores, sem fome, sem guerras, sem doenças   <br>e   nenhum   outro   mal."</u>. <br>(Savino Mombelli)</a></strong></h1>
<div id="menu">
<a href="./savinoPortugues.html" style="text-decoration:none">Savino</a>
<a href="./impressos/historiaPadreSavino.pdf"target="_blank"style="text-decoration:none">Histórico</a>
<a href="./impressos.html" style="text-decoration:none">Reflexões</a>
<a href="./imagSv.html"style="text-decoration:none">Imagens</a><br><br>
</div>
<div>
	<form action="testemunho.php" method="post">
            Nome: <input type="text" name="nome" size="50" />
            <br>
            Email: <input type="text" name="email" size="50" />
            <br>
			Testemunho: <textarea name="testemunho" rows="10" cols="100"></textarea> <br/><br/>
            <input type="submit" value="Enviar"/>
        </form> 
        <?php include("mostratestem.php"); ?>
</div>
<BLOCKQUOTE>
		<p>
		*<a href="./mostratestem.html"style="text-decoration:none"><h3>Veja os testemunhos registrados</h3></a><br><br>*
		<h2>PÁGINA EM COSTRUÇÃO </h2>
		</p>
	</BLOCKQUOTE>
</div>
</body>
</html>

  • On the page php testimony. that part here is open or die (mysqli_error($escrever); foul ) to close

1 answer

1


I was going through this problem, but now I managed to solve a few days ago and I will post my code here is a table with data brought from the database, and this way I take only the header of PHP and leave inside the HTML itself. My include in the file conn.php is done because, this file that makes connection to the database.

index.php ( test this with values from your database )

<table border = '2'>

<tr>
  <th>ID</th>
  <th>Código Produto</th>
  <th>Tipo</th>
  <th>Descricao</th>
</tr>

<?php include("conn.php");

$sql_tipo = "SELECT * FROM tipoprod";
$resulta = $conn->query($sql_tipo);

if ($resulta->num_rows > 0){

    while ( $row = $resulta->fetch_assoc()){            

        echo '<tr>';
        echo '<td>'. $row['id'] .'</td>';
        echo '<td>'. $row['codigo_produto'] .'</td>';
        echo '<td>'. $row['codigo_tipo'] .'</td>';
        echo '<td>'. $row['descricao'] .'</td>';
        echo '</tr>';
    }
}
?>
</table>

Conn.php

<?php
$servername = "localhost"; /* nome da conexão */
$username = "root"; /* nome do usuario da conexãp */
$password = ""; /*senha do banco de dados caso exista */
$dbname = "teste123"; /* nome do seu banco  */

// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
} 
?>
  • Hi Victor! Thanks for your help. Being that I am a first time browser in web development, I wanted to understand how it works (check) your Conn.php trying to relate this suggestion to my site.

  • is basically a file that Voce creates with the name you want, in my case is Conn, and you include in all pages that use connection to the bank, instead of creating connection page by page. I will edit the answer with the Conn.php file

  • I did the test using your suggestion but it did not give the expected result. See images <img src=" http://localhost/imgPv/imagStackOver1.png" width="200" height="100"> <br> <img src=" http://localhost/imgPv/imagStackOver2.png" width="400" height="100">

  • just open another question with your code and your question I help, comment here the question link and if you want to add image, select an icon in the header from where you type your message that has an image icon

  • Ok, Victor! I just didn’t know that when you have a php code inserted in html, the file has to get the php exenção. Done that, it worked WONDERFUL. Thanks my brother!

  • yes you have to always give a include in the connection file, if its name is execised for example, at the beginning of your file already open a <?php include("Conn.php); block? > and then it will work normal for the whole page

  • Okay, Victor, thanks again. I count on your help for the next obstacle in the realization of my site where will be included a very complex system in security mechanisms.

Show 2 more comments

Browser other questions tagged

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