Hello,
I have a form that receives the rows of a MySQL SELECT statement that are escaped with htmlspecialchars()
as their values.
The values may be modified and sent to the DB with an UPDATE statement, but when the form is reloaded after the UPDATE, HTML entities are in the text.
I tried htmlspecialchars_decode()
to send the form values to the DB without the HTML entities, but I think I have misunderstood how it works. I did try with the ENT_QUOTES argument as well.
Here are the concerned pieces of code:
The function that SELECTs from the DB. It is linked to a .view.php file for the rest of the HTML.
Thank you.
function tutors_courses() {
global $session_id;
$query = "SELECT tutors.tutor_id, username, CONCAT(first_name, ' ', last_name) AS tutor_name,
courses.course_id, courses.title, courses.description, courses.price FROM tutors
JOIN tutors_courses ON tutors_courses.tutor_id = tutors.tutor_id
JOIN courses ON courses.course_id = tutors_courses.course_id
WHERE tutors.tutor_id = $session_id";
global $pdo;
$result = $pdo->query($query);
while ($row = $result->fetch()) {
$title = $row['title'];
$desc = $row['description'];
$price = $row['price'];
$course_id = $row['course_id'];
$title = htmlspecialchars($title);
$desc = htmlspecialchars($desc);
$price = htmlspecialchars($price);
$course_id = htmlspecialchars($course_id);
echo <<<_TUTORSCOURSES
<form action="/update-dashboard" method="post">
<td class="queries_table-data"><input type="text" name="title" value="$title"></td>
<td class="queries_table-data"><textarea name="description" rows="3">$desc</textarea></td>
<td class="queries_table-data"><input type="number" name="price" step="any" value="$price"></td>
<td class="queries_table-data">
<input type="hidden" name="courseid" value="$course_id">
<button class="btn" type="submit" name="edit-course">Edit course</button>
</td>
</form>
<form action="/tutor-dashboard" method="post">
<input type="hidden" name="courseid" value="$course_id">
<td><button type="submit" name="delete-course" class="btn btn--delete">Delete</button></td>
</form>
<tr>
_TUTORSCOURSES;
}
}
This part is for the UPDATE that receives the above form data.
if (isset($_POST['edit-course'])) {
if (
!empty($_POST['title']) &&
!empty($_POST['description']) &&
!empty($_POST['price']) &&
!empty($_POST['courseid'])) {
echo "<H1>EDITING</h1>";
$courseid = htmlspecialchars_decode($_POST['courseid']);
$title = htmlspecialchars_decode($_POST['title']);
$desc = htmlspecialchars_decode($_POST['description']);
$price = htmlspecialchars_decode($_POST['price']);
$stmt = $pdo->prepare("UPDATE `courses` SET title=?, `description`=?, `price`=? WHERE `course_id`=?");
$stmt->bindParam(1, $title);
$stmt->bindParam(2, $desc);
$stmt->bindParam(3, $price);
$stmt->bindParam(4, $courseid);
$stmt->execute([$title, $desc, $price, $courseid]);
?>
<script>location.reload();</script>
<?php
}
}