haydenbarton96 haydenbarton96 - 7 months ago 9
SQL Question

Can't seem to get $_GET['id'] to work

I'm trying to get data from a database but cant seam to get the following working, does anyone know why?

I have tried

print_r
too and shows nothing, the db connection and everything is working too.

$id = $_GET['id'];
$query = $db->prepare('SELECT id, title, content FROM articles WHERE id = $id');
$query->execute();
$article = $query->fetchall();


This does however
print_r
the id from the URL correctly.

print_r($_GET);


Any help is appreciated!

Answer

Important note:

Variables inside single qoutes are not interpolated. They're just literal strings

Much better to bind them properly:

$id = $_GET['id'];
$query = $db->prepare('SELECT id, title, content FROM articles WHERE id = :id');
$query->bindParam(':id', $id);
$query->execute();
$article = $query->fetchAll(PDO::FETCH_ASSOC);
Comments