0

I created a page allowing persons to click a button and it should change values within a database. However, when I refresh my php file in a browser, the values that were in the database suddenly change by themselves, without having to click that button. I'm new to coding and it frustrates me.

Here's the issue :

The code in the file named collection1.php

<?php session_start();?>
<!doctype html>
<html>
        <title>
            Coming soon!
        </title>
        <meta charset="utf-8"/>
        <link rel="stylesheet" type="text/css" href="forme set.css">
        <script src="outter.js"></script>
    <head>
    </head>
    <body>
        <div>
            <button id="button1" class="button1" onclick="<?php
    $link=mysqli_connect("localhost", "root", "", "database");
    if(!isset($_SESSION['username'])){
        echo "linkerror()";
    } else {
        $username=$_SESSION['username'];
        $cardid="plot32";
        $already=mysqli_query($link, "SELECT cardid FROM cardscollection WHERE '".$cardid."' IN (cardid) AND '".$username."' IN (username)");
        if($already->num_rows!==0){
            $removeit=mysqli_query($link, "DELETE FROM cardscollection WHERE username='".$username."' AND cardid='".$cardid."'");
            $removecard=mysqli_query($link, "UPDATE accounts SET nbcards = nbcards - 1 WHERE username='".$username."'");
        } else {
            $addit=mysqli_query($link, "INSERT INTO cardscollection (username, cardid, series, subseries) VALUES ('".$username."', '".$cardid."', 'World Tourney', 'Tourney 2.2')");
            $addcard=mysqli_query($link, "UPDATE accounts SET nbcards = nbcards + 1 WHERE username='".$username."'");
        }
    }
?>"></button>
        </div>
   </body>

The database tables look like this :

Table 'accounts'

username nbcards
username1 1

Table 'cards collection'

username cardid series subseries
username1 plot32 World Tourney Tourney 2.2

Let's imagine I am username1 and click on that button. If the concerned values already are in the database, it should change the appropriate values right? But if I refresh the php file in my browser to refresh the code I am working on (here localhost/collection1.php), the database will change to this by itself, without me clicking on the button :

Table 'accounts'

username nbcards
username1 0

Table 'cards collection'

username cardid series subseries

I probably misunderstand some php/sql exchanges as I have no idea why it occurs, knowing another account registering page works fine the same way. Any help is appreciated, thanks!

No idea why it happens..

Bagetsu
  • 36
  • 5
  • 1
    PHP runs **before** the page is sent to the browser, javascript runs **after**. Any PHP you have on the page will have run by the time the page gets to the user. If you look at the source of the page in your browser, you'll see that your `onclick` is most likely empty. You'll want to look into ajax requests to do what you want. – aynber Dec 09 '22 at 18:49

0 Answers0