0

Here's the scenario. In my webpage I have 14 buttons , each one of them having unique id which is similar to the corresponding book_id stored in the database.In order to show the contents of the book I have to redirect it to next page (bookpage.php) by passing the book_id . It's working fine till here. In the bookpage.php when I try to access the id through the URL it's not working. If I set the type to int it stores the value 0 , if I don't set it to int then I get an empty page.

Here's the code of Genre.php (The first webpage)

<button class='read' id = $book_id type='submit'><h4>Free Preview </h4></button> 
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
    <script>
        $(document).ready(function() {
        $('.read').click(function() {
            const bookId = this.id;
            window.location.href = 'bookpage.php?id=' + bookId;
        }); 
    });
  </script>

Now here's the code snippet of bookpage.php (The second webpage)

 <?php
    $bookId =$_GET['id'];
    $select = "Select * from books where Book_ID = $bookId";
    $result = mysqli_query($con,$select);
    $book = $result->fetch_assoc();
    $title = $book['Title'];

For example take the URL as : http://localhost/Biblion/bookpage.php?id=A21

In this case I just get a blank page. If I write it as $bookId =(int) $_GET['id] and print the variable I get the value 0.

Thanks a lot!

Barmar
  • 741,623
  • 53
  • 500
  • 612
  • You need quotes around `$bookId` since it's a string, not a number. But the right solution is to use a prepared statement with placeholders. This will solve your problem and also protect against SQL injection. – Barmar Mar 23 '23 at 01:06
  • @Barmar Ohh. I just used the explicit type conversion (string) and it worked. Thanks for your idea! – Light Gaia Mar 23 '23 at 01:50
  • NO!!! You should always use parametrized statements to insert variables into queries. – Barmar Mar 23 '23 at 15:08
  • I don't see how a type conversion would help. Everything in `$_GET` is already a string. – Barmar Mar 23 '23 at 15:09
  • Ohh. I don't know much of the stuffs since I'm new to PHP. Well , I'll look into it. – Light Gaia Mar 25 '23 at 06:20
  • And it did work , when I used the type conversion! – Light Gaia Mar 25 '23 at 06:20
  • When you convert the string `A21` to an integer it becomes `0`. That fixes the error message, but it's not the ID you want. If you use `where Book_ID = '$bookId'` it will work, but that's not the correct way to do it. Use a prepared statement with `bind_param()` and you'll get the desired result and protect against SQL injection. – Barmar Mar 26 '23 at 16:54

0 Answers0