I'm trying to make a very simple registration form. But when I get an error that says that I have an error in my SQL syntax.
But it says that I have the problem on the line where I wrote:
$stmt->execute();
I guess it's because it can not execute the SQL question?
My code:
<?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>
Looking at your SQL query:
INSERT INTO users(username, password, namn) VALUES :username, :password, :name
spelling? -----^ ^------ parentheses ------^
The spelling one is mostly a guess, but at the very least the parentheses are a good idea. So maybe you meant this?:
INSERT INTO users(username, password, name) VALUES (:username, :password, :name)
Also, as a side note, never store user passwords in plain text . This is very irresponsible handling of user data. PHP has a lot of built-in functionality to assist in properly obscuring user passwords behind a one-way hash. (As well as a compatibility pack for older PHP versions.)
语法错误是因为您需要在值周围加上括号:
INSERT INTO MyTable (Column1, Column2) VALUES (Value1, Value2)
enclose the variables in single quotes because these are string and strings cannot be directly inserted in database. eg
INSERT INTO talbe_name (col1,col2) VALUES ('string1','string2');
also draw {}
around variables inside the string in php code eg
<?php
$str = "Value={$variable}";
?>
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.