Generating HTML Page by PHP from the database

2

I'm learning php with mysql and I use wamp.

I'm developing a site with only academic terms, and I have a problem: I have a database with 20 pilots, and every pilot has information like age, description, height, I was wanting to use PHP to make a template page, and for each pilot I could use their information, and the PHP program would change the information according to a pre-set menu, without the need for me to have to do 20 pages for each pilot, and so the PHP program would select the data from the database ...

Someone has some source from where I can find bases for this, similar solutions, codes, and bibliographies that help me to develop my abilities in PHP ...

    
asked by anonymous 23.05.2015 / 16:51

1 answer

3

Well, I'll give you an example of how I would do it, do not worry about functions you do not know, and then enjoying it, when you ask here have a code ready soon, this will make it easier for people to help you. But let's for example:

system.php:

//Constantes da conexão
define("DB_HOST","localhost");
define("DB_NAME","root");
define("DB_USER","exemplo");
define("DB_PASS","123");

//Criamos uma classe pra o sistema
class sistema
{
  //Definimos o método private para o $db_connection
  private $db_connection = null;

  //Criaremos uma conexão com o banco de dados, usando PDO
  private function databaseConnection()
        {
        // Conexao berta
        if ($this->db_connection != null)
            {
            return true;
            }
        else
            {
            // Criando a conexao com banco de dados, usando constantes
            try
                {
                $this->db_connection = new PDO('mysql:host=' . DB_HOST . ';dbname=' . DB_NAME . ';', DB_USER, DB_PASS);
                return true;
                // Tratamento de erro, caso falhe a conexao
                }
            catch (PDOException $e)
                {
                $this->errors[] = MESSAGE_DATABASE_ERROR;
                return false;
                }
            }
        }


//Criar função que acessa o sua tabela
public function buscarPilotos($nome_piloto)
{
  //Chamamos a conexão com o banco
  $this->databaseConnection();

  //Selecionaremos a tabela com o nome do piloto passado pela função, faremos uso de Prepared statements para uma melhor segurança
  $pilotos = $this->db_connection->prepare('SELECT * FROM pilotos WHERE nome_piloto = :nomedopiloto');

  //Usaremos o bindValue para passar o nome do piloto à conexão
  $pilotos->bindValue(':nomedopiloto', $nome_piloto, PDO::PARAM_STR);

  //Executar a ação para nos retornar a query
  $pilotos->execute();

  //Vamos usar o fetchAll para nos retornar uma array com os dados do piloto
  $piloto_encontrados = $pilotos->fetchAll();

  //Vamos usar a Foreach para nos listar este piloto num formato HTML, usando divs html (pode ser tabelas ou o que quiser, vou só ilustrar) 

  foreach($piloto_encontrados as $pilot)
  {
    echo '<div id="nomedopiloto">'.$pilot["nome"].'</div>
  <div id="idadedopiloto">'.$pilot["idade"].'</div>
  <div id="alturadopiloto">'.$pilot["altura"].'</div>';
  }
}


}

Ready, created the system file, we will go to the main file, where we expect to have divs already with their styles css and etc.

index.php

<?php
//Vamos incluir nosso arquivo de sistema
require("sistema.php");
?>
<!DOCTYPE html>
<html>
<head>
    <link rel="stylesheet" href="_css/estilo.css"/>
    <meta charset="UTF-8"/>
    <title>Exemplo PHP</title>
</head>
<body>
<div id="piloto">
<?php 
//Vamos iniciar nossa classe
$pegar_piloto = new sistema();
//Vamos passar o nome do piloto para a função
$pegar_piloto->buscarPilotos("Cassiano");
//Irá imprimir os resultados
?>
</div>
</body>
</html>

Please note: this is only for EXAMPLE , even though I am a bit busy, there are many techniques for entering data into HTML coming from BD using for example the good standard MVC , making use of the Dwoo project and so on. But since you are a beginner, I did it just for you to ask; "What is this? What is that?" and look for it out there in forums and etc, because the best way to learn is by asking, searching, and for sure learning the best that PHP offers, Object Orientation.

Good luck!

    
23.05.2015 / 20:35