Search code examples
phpsqlmethodsgetslug

(php) I get extra code in "get" method link


my 1st question in overflow :)

I have tried to create a table to show all posts from SQL. I have done the next code:

function show_all_posts_in_table(){
        global $connection;
        $query = "SELECT * FROM posts";
        $all_posts_content_query = mysqli_query($connection,$query);

        while ($row = mysqli_fetch_assoc($all_posts_content_query)) {
            $post_id_display = $row['post_id'];
            echo "<tr>";
            echo "<td>" . $post_id_display = $row['post_id'] . "</td>";
            echo "<td>" . $post_category_display = $row['post_category_id'] . "</td>";
            echo "<td>" . $post_title_display = $row['post_title'] . "</td>";
            echo "<td>" . $post_author_display = $row['post_author'] . "</td>";
            echo "<td>" . $post_date_display = $row['post_date'] . "</td>";
            $post_image_display = $row['post_image'];
            echo "<td>" . "<img src= '../images/{$post_image_display}' width='200' height='auto'>" . "</td>";
            echo "<td>" . $post_content_display = $row['post_content'] . "</td>";
            echo "<td>" . $post_tags_display = $row['post_tags'] . "</td>";
            echo "<td>" . $post_status_display = $row['post_status'] . "</td>";
            echo "<td>{$post_id_display}</td>";
            echo "<td> <a href='posts.php?delete={$post_id_display}'>DELETE</a> </td>";
            echo "</tr>";
}
}

i see all the posts in the table I made and everything is working fine.

the problem is when I try to delete one of the posts (delete href with "get" method).

for some reason I could not understand, on the address line of the chrome i get an extra </td>.

i've been directed to: posts.php?delete=6</td>.

can anyone understand why this is happening?

Thank you!


Solution

  • $post_id_display = $row['post_id'] . "</td>"; will set $post_id_display to the $row['post_id'] and then concatenate </td> to it.

    There's no need to store these values in separate variables. Just use the $row array directly instead.

    Change it to:

    while ($row = mysqli_fetch_assoc($all_posts_content_query)) {
        echo "<tr>";
        echo "<td>" . $row['post_id'] . "</td>";
        echo "<td>" . $row['post_category_id'] . "</td>";
        echo "<td>" . $row['post_title'] . "</td>";
        echo "<td>" . $row['post_author'] . "</td>";
        echo "<td>" . $row['post_date'] . "</td>";
        echo "<td>" . "<img src= '../images/" . $row['post_image'] . "' width='200' height='auto'>" . "</td>";
        echo "<td>" . $row['post_content'] . "</td>";
        echo "<td>" . $row['post_tags'] . "</td>";
        echo "<td>" . $row['post_status'] . "</td>";
        echo "<td>" . $row['post_id'] . "</td>";
        echo "<td> <a href='posts.php?delete=" . $row['post_id'] . "'>DELETE</a> </td>";
        echo "</tr>";
    

    ...and it should work.