简体   繁体   中英

can't get id with $_GET method

I have a problem. I'm trying to get the users ID from the link.

localhost/projekt/php/rules.php?user=1

Then i save the user ID with $ID = $_GET['user'];

It's working, but then after i press a button where i need the ID, it says: user is undefined.

Here is my code.

<?php
$conn = new mysqli('localhost', 'root', '', 'logins');

$id = $_GET["user"];

$var = 0;
if(isset($_POST['submit'])) {
    if (isset($_POST['checkbox'])) {

        $sql = "SELECT rulesaccepted FROM logins WHERE ID = '$id'";

        foreach ($conn->query($sql) as $row) {
            $sql3 = "UPDATE logins SET rulesaccepted = '1' WHERE ID = '$id'";
            $conn->query($sql3);
            header('Location: main.php');
        }   
    } else {
        $var = 1;
    }
}
?>

that's because you are redirecting to main.php which has no user attribute .

so you will need to check if the user isset .

if (isset($_GET["user"]) {
    $id = $_GET["user"];
}

and you must notice

because your code is highly vulnerable to sql injections , it's highly recommended to use prepared statements

this lines : $sql3 = "UPDATE logins SET rulesaccepted = '1' WHERE ID = '$id'"; $conn->query($sql3);

would be better to be as follows:

$sql3 = "UPDATE logins SET rulesaccepted = '1' WHERE ID=?";
$stmt = $conn->prepare($sql3);
$stmt->bind_param('i', $id);
$stmt->execute();

and same to your select query :)

I hope that when you click button the localhost/projekt/php/rules.php?user=1 don't fire again. That is why it says: user is undefined

You can use $_GET['user'] in your form as the following

<input type="hidden" name="id" value="<?php echo $_GET['user'] ?>" />

Then you can use id when button click

if(isset($_POST['submit'])) {
    if (isset($_POST['checkbox'])) {
    $id=$_POST['id']

        $sql = "SELECT rulesaccepted FROM logins WHERE ID = '$id'";

        foreach ($conn->query($sql) as $row) {
            $sql3 = "UPDATE logins SET rulesaccepted = '1' WHERE ID = '$id'";
            $conn->query($sql3);
            header('Location: main.php');
        }   
    } else {
        $var = 1;
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM