douweicheng5532 2018-11-03 15:34
浏览 47

尝试在表中插入值时,所有值都被清除

I am trying to simply insert values into a database table using PHP. but every time all the pre-inserted values are getting erased and no value insertion takes place.

<?php
$servername = "localhost";
$username = "root";
$password = "rex";
$dbname = "test";
$usr = $_POST["Username"];
$pass = $_POST["password"];

try {
    $conn = new PDO("mysql:host=$servername;dbname=$dbname", $username, $password);
    // set the PDO error mode to exception
    $conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
        $sql = "INSERT INTO users(username,password)VALUES('$usr','$pass')";
    // use exec() because no results are returned
    $conn->exec($sql);
    echo "New record created successfully";
    }
catch(PDOException $e)
    {
    echo $sql . "<br>" . $e->getMessage();
}

$conn = null;
?>
  • 写回答

2条回答 默认 最新

  • doutuo7815 2018-11-03 16:17
    关注

    This should work:

    $sql = "INSERT INTO users (username, password) VALUES (?, ?)";
    $prepared = $conn->prepare($sql);
    $prepared->execute([$usr, $pass]);
    

    This is also better since you are binding the variables.

    http://php.net/manual/en/pdo.prepare.php

    You should also sanitize your $_POST-variables. Username is also spelled with a capital U in your $_POST-variable.

    评论

报告相同问题?

悬赏问题

  • ¥15 drone 推送镜像时候 purge: true 推送完毕后没有删除对应的镜像,手动拷贝到服务器执行结果正确在样才能让指令自动执行成功删除对应镜像,如何解决?
  • ¥15 求daily translation(DT)偏差订正方法的代码
  • ¥15 js调用html页面需要隐藏某个按钮
  • ¥15 ads仿真结果在圆图上是怎么读数的
  • ¥20 Cotex M3的调试和程序执行方式是什么样的?
  • ¥20 java项目连接sqlserver时报ssl相关错误
  • ¥15 一道python难题3
  • ¥15 牛顿斯科特系数表表示
  • ¥15 arduino 步进电机
  • ¥20 程序进入HardFault_Handler