I want to use prepared statements to avoid SQL injection.
To give you an idea, this was my old code:
<?php
(connect to database = ok)
$id = str_replace ('-', ' ', $_GET['id']);
$sql = "SELECT * FROM `table-news` WHERE `id` = '$id' ORDER BY `date` DESC";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
while($row = $result->fetch_assoc()) {
?>
<div id="content">
<?php echo strtolower($row['text']);?>
</div>
<?php
}// end while
}// end if
else {
echo '0 results';
}// end else
?>
And this is the new code so far:
<?php
$pdo = new PDO('mysql:host=localhost;dbname=testdb', 'root', '');
$id = str_replace ('-', ' ', $_GET['id']);
$sql = "SELECT id, title, year, date, text FROM `table-news` WHERE id= :id ORDER BY `date` DESC";
$stmt = $pdo->prepare($sql);
$stmt->bindParam(":id", $id);
$stmt->execute();
if($result = $stmt->fetch(PDO::FETCH_ASSOC))
{
?>
<div id="content">
<?php echo strtolower($result['text']);?>
</div>
<?php
}// end if
else {
echo '0 results';
}// end else
?>
I got (at least) one problem with this new code:
The below code doesn't avoid SQL-injection. How can I transform this into a safe code using PDO ? (I really need to replace all spaces with a hyphen)
`$id = str_replace ('-', ' ', $_GET['id']);`