php - 为用户注册插入数据 PHP/PDO

标签 php mysql pdo

我正在尝试使用 PDO 创建一个用户注册页面,我以前从未使用过这个,所以我无法理解这些值是如何插入到我的表中的。

任何人都可以看到我的代码出了什么问题吗?

<?php

include_once ('/_includes/classes/connection.class.php');

$firstname = $_POST['firstname'];
$lastname = $_POST['lastname'];
$email = $_POST['email'];
$password = $_POST['password'];
$accounttype = $_POST['accounttype'];

$query = "INSERT INTO users(firstname,lastname,email,password,accounttype) VALUES ($firstname,$lastname,$email,$password,$accounttype)";
echo $query;
$count = $dbh->exec($query);
$dbh = null;

?>

<?php

$dsn = 'mysql:host=localhost;dbname=site.co.uk';
$username = 'access@site.co.uk';
$password = 'password';
$options = array(
    PDO::MYSQL_ATTR_INIT_COMMAND => 'SET NAMES utf8',
); 
$dbh = new PDO($dsn, $username, $password, $options);

$firstname = $_POST['firstname'];
$lastname = $_POST['lastname'];
$email = $_POST['email'];
$userpassword = $_POST['password'];
$accounttype = $_POST['accounttype'];

$query = "INSERT INTO users(firstname,lastname,email,password,accounttype) VALUES (:firstname,:lastname,:email,:password,:accounttype)";
$stmt = $dbh->prepare($query);
$stmt->bindParam(':firstname', $firstname);
$stmt->bindParam(':lastname', $lastname);
$stmt->bindParam(':email', $email);
$stmt->bindParam(':password', $userpassword);
$stmt->bindParam(':accounttype', $accounttype);
$stmt->execute();

?>

最佳答案

永远不要像以前那样做,因为 SQL Injections

使用准备好的语句。

http://php.net/manual/de/pdo.prepared-statements.php

<?php

require_once ('_includes/classes/connection.class.php');

$stmt = $dbh->prepare('INSERT INTO users (firstname,lastname,email,password,accounttype) VALUES (:firstname,:lastname,:email,:password,:accounttype)');
$stmt->execute(array($_POST));

出了问题的是,您忘记了您的值(value)观的引号。但是如果是准备好的语句,则不需要引号。

http://www.w3schools.com/sql/sql_insert.asp

请不要将纯文本密码保存到数据库中,使用散列

Secure hash and salt for PHP passwords

如果你确实需要包含文件,最好使用“require”或“require_once”。

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

关于php - 为用户注册插入数据 PHP/PDO,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14417547/

相关文章:

php - 在后台运行的进程挂起 PHP 页面

php - 将变量注入(inject) NSIS 安装程序

php - 如何执行条件 SQL 插入语句?

mysql - MySQL 中何时使用单引号、双引号和反引号

Mysql存储过程将表的特定列数据选择到临时表中

php - 用php连接mysql,在浏览器中查看

php - 使用 INNER JOIN 时绑定(bind)占位符变量的 PDO 异常问题

php - 如何正确使用Flysystem和Local Adapter

mysql - 更改 MySQL 中的隔离级别 (Windows)

php - 我不明白为什么DeleteTask.php不起作用,但RetrieveTask.php却起作用