Hi and welcome to Stack Overflow!
Looks like you are trying to call php function from the client (browser). This is however impossible.
The way the PHP works is, that it prepares the content for the client and sends it to the client. After it is send, you cannot interact with the PHP code anymore. What you need to do is make client send another request.
My problem is that whenever the page loads it automatically triggers the onclick event without me clicking on anything.
The page load does not trigger onclick event. The PHP looks for all
<?php and runs the code inside it even before it is sent to client.
How to do it?
You need to change the infrastructure a bit. For the beginning i'd suggest not using JS at all, but instead create second PHP page, that just does the
borrowBook using GET parameter (you can expand it later) (See PHP's $_GET)
First you need to actually create the second page (let's call it
This page will get book's id using GET parameter (let's call that
This page's code may look something like this (Note: code is not tested)
<?php borrowBook($_GET["bookid"]); header("Location: /books.php"); ?>
And now you need to change original code's line
<input type="button" value="Borrow" class="button" id="btnBorrow" onclick="<?php borrowBook($row["id"])?>">
To something like this
<a href="/borrowBook.php?bookid=<?= $row["id"] ?>">Borrow</a>
What this does is, that PHP sees
<?= and run the code inside it (in this case replaces the
?> section with value of
$row["id"]. Which if id is 1 will result in this:
Sorry for my bad english.