每次页面加载时触发按钮onclick事件

I have a button which has a onclick attribute which calls a function. My problem is that whenever the page loads it automatically triggers the onclick event without me clicking on anything.

I've tried different variatons of syntax but nothing worked. I swapped 'button' for 'input type=button' but that didn't help anything.

this is in books.php

$sql = "SELECT books.id, books.name as bookname, authors.name as authorname, autori.surname, genre, description, stock FROM books JOIN authors ON books.author_id=authors.id ORDER BY books.name ASC";
$result = $conn->query($sql);

if ($result->num_rows > 0) {
    echo "<table><tr><th>Name of the book</th><th>Author</th><th>Copies available</th></tr>";

    while($row = $result->fetch_assoc()) {
        echo "<tr><td>".$row["bookname"]."</td><td>".$row["authorname"]." ".$row["surname"]."</td><td>".$row["stock"]."</td>";

        if (isAvailable($row["id"]) && isset($_SESSION["id"])) {
            ?>
            <td><input type="button" value="Borrow" class="button" id="btnBorrow" onclick="<?php borrowBook($row["id"])?>"></td></tr>

and I'm calling the function borrowBook from functions.php which looks like this.

function borrowBook($idbook) {
    $servername = "aaa";
    $username = "bbb";
    $password = "ccc";
    $dbname = 'ddd';
    $iduser = $_SESSION["id"];

    $conn = new mysqli($servername, $username, $password, $dbname);
    if ($conn->connect_error) {
        die("Connection failed: " . $conn->connect_error);
    }

    $sql = "UPDATE books SET stock = stock - 1 where id = " . $idbook;
    $conn->query($sql);

    $sql = "INSERT INTO reservations(id, dateBorrowed, dateReturn, returned, kniha_id, uzivatel_id) VALUES (NULL, NOW(), DATE_ADD(NOW(), INTERVAL 34 DAY), 0, $idbook, $iduser)";
    $conn->query($sql);
}

So the SQL query and everything actually works. When I check the database I actually get new entries and everything is as expected. The only problem I'm having is that the button's onclick event is always triggered on every page load and I can't seem to fix it. From searching online everybody is using stuff like JavaScript or jQuery so it didn't really help me.

查看全部
doujing6053
doujing6053
2019/01/28 18:09
  • php
  • html
  • 点赞
  • 收藏
  • 回答
    私信
满意答案
查看全部

2个回复