How to treat ids with php?

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 the existing news headlines. As you can see, I also added a link to each of them. But I'd like to know how to handle each of the ids on a next page, to the user clicking on the linked link to 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'];
    }

    ?>
    
asked by anonymous 21.07.2017 / 01:57

1 answer

5

After this line

$id = $_GET['id'];

Treat the received value before proceeding with other actions.

Normally the ID is numeric, then considering it to be a numeric 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 type of data received from a form?

    
21.07.2017 / 03:47