isset value always returns 1

I am a newbie when it comes to PHP. I am trying to make a login and logout webpage. Now, I have created a page which would add records. MY code always returns 1 from the form that i built, irrespective of the value in the form.
My code-

<?php
    $servername = "localhost";
    $username = "username";
    $password = "password";
    $alpha = isset($_GET["username"]);
    $beta = isset($_GET["password"]);
    $gama = isset($_GET["hobby"]);
    // Create connection
    $conn = mysqli_connect("localhost","root" ,"","member");

    // Check connection
    if (!$conn) {
        die("Connection failed: " . mysqli_connect_error());
    }

    $sql = "INSERT INTO data (username,password,hobby)
        VALUES ($alpha, $beta, $gama)";

    if ($conn->query($sql)=== TRUE) {
        echo $alpha."Your record is added into our database ";
    } else {
        echo $sql.$conn->error;
    }                                          
?>

And this is my form:

<form action="add.php">
  <table> 
    <tr>
        <td>Username :</td>  <td><input type="text" name="username"></td>
    </tr>
    <tr>    
        <td>Password :</td>   <td><input type="text" name="username"></td>
    </tr>
    <tr>
        <td>Hobbies:</td>   <td><textarea name="hobby" id="hobby" cols="22" rows="7"></textarea></td>
    </tr>
    <tr>
        <td>    </td><td><input type="submit" name="submit"></td>
    </tr>

  </table>
</form>

Here is Solutions:

We have many solutions to this problem, But we recommend you to use the first solution because it is tested & true solution that will 100% work for you.

Solution 1

It happens because isset() returns a boolean value.

If you want to directly print the username field you can just:

if(isset($_GET["username"])) { 
    echo $_GET["username"];
}

So you should understand that the variables $alpha, $beta, $gamma do not hold the actual string you expect but a boolean value

See more at: http://php.net/manual/en/function.isset.php

Solution 2

Its because the isset() function checks whether the key in an array is set or not it doesn’t checks whether the value is set or not. In your case; when you post your form to the action the POST array contains all the keys hence isset returning 1 as usual. I think you need to have a look at php empty() function. Or you might want to use the mixture of isset() and empty().

http://php.net/manual/en/function.empty.php

Note: Use and implement solution 1 because this method fully tested our system.
Thank you 🙂

All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply