doumo3903 2017-02-13 10:19
浏览 26
已采纳

变量未插入表[重复]

This question already has an answer here:

I have a very simple code to insert data into database, also checks if already has same data in table

[HTML]

<html>
<head>
    <title>nickname</title>
</head>
<body>
    <p>input nickname</p>
    <form action="foo.php" method="post">
        <input type="text" name="nickname" />
        <input type="submit">
    </form>
</body>
</html>

[PHP]

//foo.php
if(isset($_POST['nickname']) && !empty($_POST['nickname'])) {
    $nickname = $_POST['nickname'];

    //Object Oriented way
    $servername = "localhost";
    $username = "root";
    $password = "foo_bar";
    $dbname = "nickname";

    //check connection
    $conn = new mysqli($servername, $username, $password, $dbname);

    if($conn->connect_error) {
        die("cannot connect:".$conn->connect_error);
    }

    $sql = "SELECT * FROM nickname WHERE nickname='$nickname'";
    $result = $conn->query($sql);

    if($result->num_rows > 0) {
        echo "nickname exists!";
    } else {
        $sql = "INSERT INTO nickname(nickname) VALUES(".$nickname.")";
        $conn->query($sql);
        echo "welcome $nickname!";
    }

    $conn->close();

} else {
    echo "please input your nickname";
}

I am still learning how to use MySQL, what am I doing wrong? especially this line

$sql = "INSERT INTO nickname(nickname) VALUES(".$nickname.")";
$conn->query($sql);

the data in the variable is not inserted to table, nothing happens. but if I replace $nickname to plain text the data is inserted.

edit
why is this a duplicate? the question is not even about "how to prevent sql injection"

</div>
  • 写回答

1条回答 默认 最新

  • doumi4676 2017-02-13 10:23
    关注

    Give single quotes for the variable

    $sql = "INSERT INTO nickname(nickname) VALUES('".$nickname."')";
    $conn->query($sql);
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 基于卷积神经网络的声纹识别
  • ¥15 Python中的request,如何使用ssr节点,通过代理requests网页。本人在泰国,需要用大陆ip才能玩网页游戏,合法合规。
  • ¥100 为什么这个恒流源电路不能恒流?
  • ¥15 有偿求跨组件数据流路径图
  • ¥15 写一个方法checkPerson,入参实体类Person,出参布尔值
  • ¥15 我想咨询一下路面纹理三维点云数据处理的一些问题,上传的坐标文件里是怎么对无序点进行编号的,以及xy坐标在处理的时候是进行整体模型分片处理的吗
  • ¥15 CSAPPattacklab
  • ¥15 一直显示正在等待HID—ISP
  • ¥15 Python turtle 画图
  • ¥15 stm32开发clion时遇到的编译问题