Home > database >  PHP displays only one word from MySQL record in URL variable
PHP displays only one word from MySQL record in URL variable

Time:10-26

A PHP page displays only one word from a MySQL record in a URL variable, while it displays the correct 2 words in the HTML output, I tried many solutions such '".$row['book_category']."' and {$row['book_category']} etc. but I still get the same one result.

<?php
    foreach($conn->query('SELECT book_category, COUNT(*) FROM books GROUP BY book_category') as $row) {
        echo "<tr>";
        echo "<td>" . "<a href=" . "sidebar_cat_display.php?book_cat=" . $row['book_category'] . ">" . $row['book_category'] . "</a>" . "</td>";
        echo "</tr>"; 
    }
?>

So now first $row insert is only one word in the url, while the second $row outputs two words properly as expected; the problem is I need the two words to be passed as variable in the URL.

CodePudding user response:

URLs cannot have a space character, this is why you are seeing the first word only, you need to encode the value received using rawurlencode().

<?php
    foreach($conn->query('SELECT book_category, COUNT(*) FROM books GROUP BY book_category') as $row) {
        echo "<tr>";
        echo "<td>" . "<a href='sidebar_cat_display.php?book_cat=" . rawurlencode($row['book_category']) . "'>" . $row['book_category'] . "</a>" . "</td>";
        echo "</tr>"; 
    }
?>

Keep in mind you will also need to adjust the sidebar_cat_display.php page to fetch the book_cat parameter from the URL accordingly if you aren't already.

  • Related