Search code examples
phppdogetfetch

How to safely use $_GET['id'] to get details from database by selecting html table row


So, I have this working code to click on a link for showing details from one row of a database on another page in input text boxes.:

    <?php
            foreach ($allCentrifuge as $list) {
                $id = $list['id'];
                ?>
                <tr>
                    <td><?php echo $list['experiment'] ?></td>
                    <td><?php echo $list['project_name'] ?></td>
                    <td><?php echo $list['project_date'] ?></td>
                    <td><a href="../Views/user_centrifuge.php?id=<?php echo $list['id']?>">Details</a></td>
                </tr>
                <?php
            }
            ?>

And this function to get those details:

    public function fetchCentrifuge()
    {

        $uid = $_GET['id'];

        try {

            $stmt = $this->dbconn->prepare("SELECT * FROM centrifuge WHERE id = ?");
            $stmt->execute(array($uid));
            return $stmt->fetchAll();
        }

So, obvious from all the subjects I read, this is dangerous to SQL injection. But how do I use this code with prepared statements? I can't seem to get it work with the id placeholder.


Solution

  • Looks good as is. You could additionally cast your input var to INT.

    (int)$_GET['id'] or intval($_GET['id'])