Generating HTML Page by PHP from the database

Asked

Viewed 3,079 times

3

I am learning php with mysql and use wamp.

I’m developing a site for academic-only terms, and I have a problem: I have a database with 20 pilots, and each 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-menuestablished, without the need for me to have to make 20 pages for each pilot, and so the PHP program selected the database data...

Does anyone have any source from where I can find grounds for this, similar solutions, codes, and bibliographies that help me develop my PHP skills...

  • would like to access the data by ID, and each item would be a link,...

  • There are several ways to implement this... you already have some code so we can take a look and work on it?

  • so Ricardo Brgweb, I already have the code of my site and the template page, but the only thing left is to call the corresponding data when the person selects the link, basically what I lack is this link between the database and PHP that I want to do for the database

  • Put your page code in the question and the format of the database columns... the best way to do this, including as learning, is by using object-oriented PHP.

1 answer

3


Well, I’ll give you an example of how more or less I would do, don’t worry about functions you don’t know, and then taking advantage, when you ask here have a code half done, it will make it easier for people to help you. But let’s go to the example:

php system.:

//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 hope to have the 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>

Note: this I did was only for EXAMPLE, even because I’m kind of busy, there are many techniques to insert data into HTML coming from BD, using for example the good pattern MVC, making use of the project Dwoo and so on. But since you’re a beginner, I did it just to ask you; "What is it? , what is that?" and seek it out in forums and so on, because the best way to learn is to ask, seek, and surely learn soon the best that the PHP offers, the Object Orientation.

Good luck!

  • 1

    poooww, man, thank you so much, it’ll help a lot!!

  • The Disposition ;)

Browser other questions tagged

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