【问题标题】:isset value always returns 1isset 值始终返回 1
【发布时间】:2017-08-10 13:46:27
【问题描述】:

我是 PHP 新手。我正在尝试制作登录和注销网页。现在,我创建了一个可以添加记录的页面。无论表单中的值如何,我的代码总是从我构建的表单中返回 1。 我的代码-

<?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;
    }                                          
?>

这是我的表格:

<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>

【问题讨论】:

标签: php sql phpmyadmin isset


【解决方案1】:

这是因为isset() 返回一个布尔值。

如果您想直接打印username 字段,您可以:

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

所以你应该明白变量$alpha$beta$gamma 不包含您期望的实际字符串,而是一个布尔值

查看更多信息:http://php.net/manual/en/function.isset.php

【讨论】:

  • 这是正确的。另请注意,尝试通过这样的直接查询插入用户数据是一种极其危险的做法。请搜索sql注入攻击和PDO主题
  • 你是绝对正确的。但问题是关于 isset 的行为。
【解决方案2】:

因为 isset() 函数检查数组中的键是否已设置,它不检查值是否已设置。在你的情况下;当您将表单发布到操作时,POST 数组包含所有键,因此 isset 像往常一样返回 1。我认为你需要看看 php empty() 函数。或者你可能想混合使用 isset() 和 empty()。

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

【讨论】:

  • OP 也会有同样的问题,因为他们使用布尔结果作为要插入的数据。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-09-25
  • 2011-04-01
  • 1970-01-01
  • 1970-01-01
  • 2016-12-17
  • 1970-01-01
相关资源
最近更新 更多