How to pull information from the database in an organized way

Asked

Viewed 64 times

-1

Good morning, I am developing a web project using PHP and Mysql.

And I came to a part of this project, where I need to get the information that was recorded in the comic book.

For example: I registered a holder and 2 dependents (3 people). The dependents are linked to the Holder through an ID (ID - Primary Holder Key / HOLDER - Foreign Dependent Key). What I need is to fetch all dependents who are bound to the holder by that ID and then display them together with the Holder in question.

I’m a complete beginner in PHP and Mysql, so forgive me grotesque errors. (The code hasn’t been refactored yet.)

Here’s the select I used to try to do that:

include_once('dbcon.php');
  $id = $_SESSION['id']; 
  $consult = "SELECT * FROM dependentes FULL OUTER JOIN dental ON dependentes.titular = dental.id";
  $result_sql = mysqli_query($conn, $consult);

And this is where I display the result:

<div class="col-md-6 centro">
          <?php
            while($data = mysqli_fetch_assoc($result_sql)){
          ?>
            <div class="col-sm-12 dados">
              <h3><?php echo $data["tipo_user"]; ?></h3>
              <h5>Nome: <?php echo $data["nome"]; ?></h5>
              <h5>CPF: <?php echo $data["cpf"]; ?></h5>
            </div>
          <?php } ?>
        </div>

So far ok, the problem is that when displaying the data it pulls all the dependent table data, or if I reverse:

$consult = "SELECT * FROM dental FULL OUTER JOIN dependentes ON  dental.id = dependentes.titular";
  $result_sql = mysqli_query($conn, $consult);

It pulls all data from the dental table (Holders).

I wanted to make a mix of the two, for example: I registered a Holder (Primary Key(AI) ID: 55). And then I registered 3 dependents in it and each received the foreign key (holder: 55) that makes the connection between them.

Now I want to show the owner and the dependents who are related to it.

Thanks in advance for the time devoted to each answer.

1 answer

0

From what I understand the difficulty is in query the database and not in printing the records using PHP. Anyway I believe that you are looking for CROSS JOIN...

SELECT * FROM dental CROSS JOIN dependentes ON dental.id = dependentes.titular;

Or you can do so too

SELECT * FROM dental, dependentes WHERE dental.id = dependentes.titular;

The query will return 1 record for each dependent, the data of the holder will be in the columns. Ai just organize and show the results in the best way for your system.

Browser other questions tagged

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