How to handle ids with php?

Asked

Viewed 86 times

4

    while ($row = mysqli_fetch_array($result)) {                
             echo "<li class='list-inline-item'><a href='news.php?id=" .$row['id']. "'>". $row['titulo'] ."</a></li>";
             echo "<br>";
}

I have this little code that searches the bank for all existing news titles. As you can see, I also added a link to each one. But I would like to know how to treat each of the ids on a following page, when the user click on the linked title open a page with more information.

-

<?php
    include("config.php");
    if(isset($_GET["id"]))
    {
    $id = $_GET['id'];

    $listagem = "SELECT * FROM noticia WHERE id = $id";
    $result = mysqli_query($conexao, $listagem);
    $linha = mysqli_fetch_assoc($result);

    echo $linha['titulo'];
    echo "<br>";
    echo $linha['news'];
    }

    ?>
  • 1

    In the archive news.php, you can recover the value of idusing $_GET["id"]. This is the question?

  • Basically yes. I’m still trying to imagine how it would be done, but thanks! I’ll try to look for some examples here.

  • To select the other registration information, just do the select in the database returning the record that has the id equal to $_GET["id"]

  • If a file already exists news.php, make a print_r($_GET['id']) on it. So when you click on the link, this id will be printed on the body of news.php. Once you’ve done that, you can just make one SELECT titulo, conteudo FROM noticias WHERE id = {$_GET[id]} and print the result of the consultation, all of this in news.php. There must already be related questions here.

1 answer

5


After that line

$id = $_GET['id'];

Take a treatment of the amount received before proceeding with other actions.

Normally the ID is numerical, so considering it to be a numerical value, Sanitize and validate

function NumberSanitize($str) {
    // retorna somente caracteres numéricos
    return preg_replace('#[^0-9]#', '', mb_convert_kana($str, 'n'));
}

$id = NumberSanitize($_GET['id']);

// Se não for vazio, prossegue
if (!empty($id)) {

    // Não precisa se preocupar com injeção SQL pois a variável possuirá somente caracteres numéricos. Portanto, pode prosseguir com a consulta ao banco.

    $listagem = "SELECT * FROM noticia WHERE id = $id";
    $result = mysqli_query($conexao, $listagem);
    $linha = mysqli_fetch_assoc($result);

    echo $linha['titulo'];
    echo "<br>";
    echo $linha['news'];
}

See also:

How to validate each data type received from a form?

Browser other questions tagged

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