我正在尝试制作一个非常简单的注册表。但是当我收到一个错误,说我的 SQL 语法有错误时。
但它说我在我写的那行有问题:
$stmt->execute();
我想是因为它无法执行SQL问题?
我的代码:
<?php
require 'anslut.php';
$submit = filter_input(INPUT_POST, "submit", FILTER_SANITIZE_SPECIAL_CHARS);
$output = "";
if (isset($submit)) {
$name = filter_input(INPUT_POST, "name", FILTER_SANITIZE_SPECIAL_CHARS);
$username = filter_input(INPUT_POST, "username", FILTER_SANITIZE_SPECIAL_CHARS);
$password = filter_input(INPUT_POST, "password", FILTER_SANITIZE_SPECIAL_CHARS);
if ($name == "" || $username == "" || $password == "") {
$output .= "All fields must be entered";
} else {
$sql = "INSERT INTO users(username, password, namn) VALUES :username, :password, :name";
$stmt = $dbh->prepare($sql);
$stmt->bindParam(":username", $username, PDO::PARAM_STR);
$stmt->bindParam(":password", $password, PDO::PARAM_STR);
$stmt->bindParam(":name", $name, PDO::PARAM_STR);
$stmt->execute();
$output .= "Registration successful";
$output .= "<a href='index.php'>Follow the link to log in</a>";
}
}
?>
<html>
<head>
<title>Register here</title>
<meta charset="UTF-8">
</head>
<body>
<form method="POST">
<table>
<tr>
<td><label>Your name:</label></td>
<td><input type="text" name="name" placeholder="Your name"></td>
</tr>
<tr>
<td><label>Username:</label></td>
<td><input type="text" name="username" placeholder="Username"></td>
</tr>
<tr>
<td><label>Password:</label></td>
<td><input type="password" name="password" placeholder="Password"></td>
</tr>
<tr>
<td></td>
<td><button type="submit" name="submit">Register</button></td>
</tr>
</table>
</form>
<?php print($output); ?>
</body>
</html>
查看您的 SQL 查询:
INSERT INTO users(username, password, namn) VALUES :username, :password, :name
spelling? -----^ ^------ parentheses ------^
拼写主要是猜测,但至少括号是个好主意。 所以也许你的意思是这个?
INSERT INTO users(username, password, name) VALUES (:username, :password, :name)
此外,作为旁注,切勿以纯文本形式存储用户密码。 这是对用户数据的非常不负责任的处理。 PHP 具有许多内置功能来帮助正确隐藏单向哈希背后的用户密码。 (以及旧版 PHP 的兼容包。
语法错误是因为您的值需要用括号括起来:
INSERT INTO MyTable (Column1, Column2) VALUES (Value1, Value2)
将
变量括在单引号中,因为这些变量是字符串,字符串不能直接插入到数据库中。
例如INSERT INTO talbe_name (col1,col2) VALUES ('string1','string2');
还可以在 PHP 代码中的字符串内变量周围绘制{}
,例如
<?php
$str = "Value={$variable}";
?>