无法使用 PHP 将用户添加到 MySQL 数据库,错误代码 #1064
Unable to add user to MySQL database using PHP, error code #1064
更新:
我最初的问题是关于将用户添加到数据库的问题。它已解决,但现在我无法登录 (login.php)。我的数据库有一个当前电子邮件条目 test@test.com ,但是当我尝试使用此电子邮件登录时,它显示 "Login failed".
我试图将初始问题的解决方案合并到 login.php 但似乎代码已经存在。所以我卡住了...这是我的 register.php 页面和我的 login.php 页面。
我觉得它与 :email
有某种关系。我的 login.php 文件有什么问题?
register.php
<?php
// First we execute our common code to connection to the database and start the session
require("common.php");
// This if statement checks to determine whether the registration form has been submitted
// If it has, then the registration code is run, otherwise the form is displayed
if(!empty($_POST))
{
// Ensure that the user has entered a non-empty username
if(empty($_POST['email']))
{
// Note that die() is generally a terrible way of handling user errors
// like this. It is much better to display the error with the form
// and allow the user to correct their mistake. However, that is an
// exercise for you to implement yourself.
die("Please enter an email.");
}
// Make sure the user entered a valid E-Mail address
// filter_var is a useful PHP function for validating form input, see:
// http://us.php.net/manual/en/function.filter-var.php
// http://us.php.net/manual/en/filter.filters.php
if(!filter_var($_POST['email'], FILTER_VALIDATE_EMAIL))
{
die("Invalid E-Mail Address");
}
// Now we perform the same type of check for the email address, in order
// to ensure that it is unique.
$query = "
SELECT
1
FROM users
WHERE
email = :email
";
$query_params = array(
':email' => $_POST['email']
);
try
{
$stmt = $db->prepare($query);
$result = $stmt->execute($query_params);
}
catch(PDOException $ex)
{
die("Failed to run query: ");
}
$row = $stmt->fetch();
if($row)
{
die("This email address is already registered");
}
// An INSERT query is used to add new rows to a database table.
// Again, we are using special tokens (technically called parameters) to
// protect against SQL injection attacks.
$query = "
INSERT INTO users (
email
) VALUES (
:email
)
";
$query_params = array(
':email' => $_POST['email']
);
try
{
$stmt = $db->prepare($query);
$result = $stmt->execute($query_params);
}
catch(PDOException $ex)
{
die("Failed to run query: ");
}
// This redirects the user back to the login page after they register
header("Location: login.php");
// Calling die or exit after performing a redirect using the header function
// is critical. The rest of your PHP script will continue to execute and
// will be sent to the user if you do not die or exit.
die("Redirecting to login.php");
}
?>
<h1>Register</h1>
<form action="register.php" method="post">
E-Mail:<br />
<input type="text" name="email" value="" />
<br /><br />
<input type="submit" value="Register" />
</form>
login.php
<?php
// First we execute our common code to connection to the database and start the session
require("common.php");
// This if statement checks to determine whether the login form has been submitted
// If it has, then the login code is run, otherwise the form is displayed
if(!empty($_POST))
{
// This query retreives the user's information from the database using
// their email.
$query = "
SELECT
email
FROM users
WHERE
email = :email
";
// The parameter values
$query_params = array(
':email' => $_POST['email']
);
try
{
// Execute the query against the database
$stmt = $db->prepare($query);
$result = $stmt->execute($query_params);
}
catch(PDOException $ex)
{
// Note: On a production website, you should not output $ex->getMessage().
// It may provide an attacker with helpful information about your code.
die("Failed to run query: " . $ex->getMessage());
}
// This variable tells us whether the user has successfully logged in or not.
// We initialize it to false, assuming they have not.
// If we determine that they have entered the right details, then we switch it to true.
$login_ok = false;
// Retrieve the user data from the database. If $row is false, then the email
// they entered is not registered.
$row = $stmt->fetch();
// If the user logged in successfully, then we send them to the private members-only page
// Otherwise, we display a login failed message and show the login form again
if($login_ok)
{
// This stores the user's data into the session at the index 'user'.
// We will check this index on the private members-only page to determine whether
// or not the user is logged in. We can also use it to retrieve
// the user's details.
$_SESSION['user'] = $row;
// Redirect the user to the private members-only page.
header("Location: private.php");
die("Redirecting to: private.php");
}
else
{
// Tell the user they failed
print("Login Failed.");
}
}
?>
<h1>Login</h1>
<form action="login.php" method="post">
Email:<br />
<input type="text" name="email" value="My Email" />
<br /><br />
<input type="submit" value="Login" />
</form>
<a href="register.php">Register</a>
谢谢!
您可以忽略下面的文字。
老问题(register.php):
我正在尝试为我的站点创建一个简单的登录系统,registration/login 只需要一个电子邮件地址。当我尝试使用 phpMyAdmin 将用户添加到数据库时出现问题,我收到错误消息(更多内容见下文)。
我已经使用以下方法成功创建了 MySQL 数据库:
CREATE TABLE `users` (
`email` varchar(255) COLLATE utf8_unicode_ci NOT NULL,
PRIMARY KEY (`email`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci AUTO_INCREMENT=1;
然后在 register.php 页面上我有这个代码。
<?php
// First we execute our common code to connection to the database and start the session
require("common.php");
// This if statement checks to determine whether the registration form has been submitted
// If it has, then the registration code is run, otherwise the form is displayed
if(!empty($_POST))
{
// Ensure that the user has entered a non-empty username
if(empty($_POST['email']))
{
// Note that die() is generally a terrible way of handling user errors
// like this. It is much better to display the error with the form
// and allow the user to correct their mistake. However, that is an
// exercise for you to implement yourself.
die("Please enter an email.");
}
// Make sure the user entered a valid E-Mail address
// filter_var is a useful PHP function for validating form input, see:
// http://us.php.net/manual/en/function.filter-var.php
// http://us.php.net/manual/en/filter.filters.php
if(!filter_var($_POST['email'], FILTER_VALIDATE_EMAIL))
{
die("Invalid E-Mail Address");
}
// Now we perform the same type of check for the email address, in order
// to ensure that it is unique.
$query = "
SELECT
1
FROM users
WHERE
email = :email
";
$query_params = array(
':email' => $_POST['email']
);
try
{
$stmt = $db->prepare($query);
$result = $stmt->execute($query_params);
}
catch(PDOException $ex)
{
die("Failed to run query: ");
}
$row = $stmt->fetch();
if($row)
{
die("This email address is already registered");
}
// An INSERT query is used to add new rows to a database table.
// Again, we are using special tokens (technically called parameters) to
// protect against SQL injection attacks.
$query = "
INSERT INTO users (
email
) VALUES (
:email
)
";
// This redirects the user back to the login page after they register
header("Location: login.php");
// Calling die or exit after performing a redirect using the header function
// is critical. The rest of your PHP script will continue to execute and
// will be sent to the user if you do not die or exit.
die("Redirecting to login.php");
}
?>
<h1>Register</h1>
<form action="register.php" method="post">
E-Mail:<br />
<input type="text" name="email" value="" />
<br /><br />
<input type="submit" value="Register" />
</form>
问题可能是由于这段代码造成的:
INSERT INTO users (
email
) VALUES (
:email
)
这是导致我在 phpMyAdmin 中出现问题的代码。它给了我这个错误:
#1064 - You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near ':email
)' at line 4
register.php 页面已成功连接到我的数据库,并且也在按预期重定向我,所以我觉得问题出在添加用户上。
问题是 mysql 不知道是什么:电子邮件是...尝试...
$email = mysql_real_escape_string($_POST['email']);
$query = "
INSERT INTO users (
email
) VALUES (
'$email'
)
";
使用
":email"
这可能有用...
您的 INSERT 语句似乎没有执行查询或分配电子邮件参数。
低于
$query = "
INSERT INTO users (
email
) VALUES (
:email
)
";
添加
$query_params = array(
':email' => $_POST['email']
);
try
{
$stmt = $db->prepare($query);
$result = $stmt->execute($query_params);
}
catch(PDOException $ex)
{
die("Failed to run query: ");
}
我 added/adjusted 你的代码。我使用了不同的占位符名称来简化调试
<?php
// First we execute our common code to connection to the database and start the session
require("common.php");
// This if statement checks to determine whether the registration form has been submitted
// If it has, then the registration code is run, otherwise the form is displayed
if(!empty($_POST))
{
// Ensure that the user has entered a non-empty username
if(empty($_POST['email']))
{
// Note that die() is generally a terrible way of handling user errors
// like this. It is much better to display the error with the form
// and allow the user to correct their mistake. However, that is an
// exercise for you to implement yourself.
die("Please enter an email.");
}
// Make sure the user entered a valid E-Mail address
// filter_var is a useful PHP function for validating form input, see:
// http://us.php.net/manual/en/function.filter-var.php
// http://us.php.net/manual/en/filter.filters.php
if(!filter_var($_POST['email'], FILTER_VALIDATE_EMAIL))
{
die("Invalid E-Mail Address");
}
// Now we perform the same type of check for the email address, in order
// to ensure that it is unique.
$checkSQL = <<<SQL1
SELECT
1
FROM users
WHERE
email = :checkemail
SQL1;
$insertSQL = <<<SQL2
INSERT INTO users (
email
) VALUES (
:insertemail
)
SQL2;
try
{
$s_ps = $db->prepare($checkSQL);
$s_ps -> bindValue(':checkemail',$_POST['email'],PDO::PARAM_STR);
$s_ps -> execute();
$checkRow = $s_ps->fetch();
if($checkRow)
{
die("This email address is already registered");
}
// An INSERT query is used to add new rows to a database table.
// Again, we are using special tokens (technically called parameters) to
// protect against SQL injection attacks.
$i_ps=$db -> prepare($insertSQL);
$i_ps -> bindValue(':insertemail',$_POST['email'],PDO::PARAM_STR);
$i_ps -> execute();
}
catch(PDOException $ex)
{
die("Failed to run query: ".$ex->getMessage());
}
// This redirects the user back to the login page after they register
header("Location: login.php");
// Calling die or exit after performing a redirect using the header function
// is critical. The rest of your PHP script will continue to execute and
// will be sent to the user if you do not die or exit.
die("Redirecting to login.php");
}
?>
<h1>Register</h1>
<form action="register.php" method="post">
E-Mail:<br />
<input type="text" name="email" value="" />
<br /><br />
<input type="submit" value="Register" />
</form>
更新:
我最初的问题是关于将用户添加到数据库的问题。它已解决,但现在我无法登录 (login.php)。我的数据库有一个当前电子邮件条目 test@test.com ,但是当我尝试使用此电子邮件登录时,它显示 "Login failed".
我试图将初始问题的解决方案合并到 login.php 但似乎代码已经存在。所以我卡住了...这是我的 register.php 页面和我的 login.php 页面。
我觉得它与 :email
有某种关系。我的 login.php 文件有什么问题?
register.php
<?php
// First we execute our common code to connection to the database and start the session
require("common.php");
// This if statement checks to determine whether the registration form has been submitted
// If it has, then the registration code is run, otherwise the form is displayed
if(!empty($_POST))
{
// Ensure that the user has entered a non-empty username
if(empty($_POST['email']))
{
// Note that die() is generally a terrible way of handling user errors
// like this. It is much better to display the error with the form
// and allow the user to correct their mistake. However, that is an
// exercise for you to implement yourself.
die("Please enter an email.");
}
// Make sure the user entered a valid E-Mail address
// filter_var is a useful PHP function for validating form input, see:
// http://us.php.net/manual/en/function.filter-var.php
// http://us.php.net/manual/en/filter.filters.php
if(!filter_var($_POST['email'], FILTER_VALIDATE_EMAIL))
{
die("Invalid E-Mail Address");
}
// Now we perform the same type of check for the email address, in order
// to ensure that it is unique.
$query = "
SELECT
1
FROM users
WHERE
email = :email
";
$query_params = array(
':email' => $_POST['email']
);
try
{
$stmt = $db->prepare($query);
$result = $stmt->execute($query_params);
}
catch(PDOException $ex)
{
die("Failed to run query: ");
}
$row = $stmt->fetch();
if($row)
{
die("This email address is already registered");
}
// An INSERT query is used to add new rows to a database table.
// Again, we are using special tokens (technically called parameters) to
// protect against SQL injection attacks.
$query = "
INSERT INTO users (
email
) VALUES (
:email
)
";
$query_params = array(
':email' => $_POST['email']
);
try
{
$stmt = $db->prepare($query);
$result = $stmt->execute($query_params);
}
catch(PDOException $ex)
{
die("Failed to run query: ");
}
// This redirects the user back to the login page after they register
header("Location: login.php");
// Calling die or exit after performing a redirect using the header function
// is critical. The rest of your PHP script will continue to execute and
// will be sent to the user if you do not die or exit.
die("Redirecting to login.php");
}
?>
<h1>Register</h1>
<form action="register.php" method="post">
E-Mail:<br />
<input type="text" name="email" value="" />
<br /><br />
<input type="submit" value="Register" />
</form>
login.php
<?php
// First we execute our common code to connection to the database and start the session
require("common.php");
// This if statement checks to determine whether the login form has been submitted
// If it has, then the login code is run, otherwise the form is displayed
if(!empty($_POST))
{
// This query retreives the user's information from the database using
// their email.
$query = "
SELECT
email
FROM users
WHERE
email = :email
";
// The parameter values
$query_params = array(
':email' => $_POST['email']
);
try
{
// Execute the query against the database
$stmt = $db->prepare($query);
$result = $stmt->execute($query_params);
}
catch(PDOException $ex)
{
// Note: On a production website, you should not output $ex->getMessage().
// It may provide an attacker with helpful information about your code.
die("Failed to run query: " . $ex->getMessage());
}
// This variable tells us whether the user has successfully logged in or not.
// We initialize it to false, assuming they have not.
// If we determine that they have entered the right details, then we switch it to true.
$login_ok = false;
// Retrieve the user data from the database. If $row is false, then the email
// they entered is not registered.
$row = $stmt->fetch();
// If the user logged in successfully, then we send them to the private members-only page
// Otherwise, we display a login failed message and show the login form again
if($login_ok)
{
// This stores the user's data into the session at the index 'user'.
// We will check this index on the private members-only page to determine whether
// or not the user is logged in. We can also use it to retrieve
// the user's details.
$_SESSION['user'] = $row;
// Redirect the user to the private members-only page.
header("Location: private.php");
die("Redirecting to: private.php");
}
else
{
// Tell the user they failed
print("Login Failed.");
}
}
?>
<h1>Login</h1>
<form action="login.php" method="post">
Email:<br />
<input type="text" name="email" value="My Email" />
<br /><br />
<input type="submit" value="Login" />
</form>
<a href="register.php">Register</a>
谢谢!
您可以忽略下面的文字。
老问题(register.php):
我正在尝试为我的站点创建一个简单的登录系统,registration/login 只需要一个电子邮件地址。当我尝试使用 phpMyAdmin 将用户添加到数据库时出现问题,我收到错误消息(更多内容见下文)。
我已经使用以下方法成功创建了 MySQL 数据库:
CREATE TABLE `users` (
`email` varchar(255) COLLATE utf8_unicode_ci NOT NULL,
PRIMARY KEY (`email`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci AUTO_INCREMENT=1;
然后在 register.php 页面上我有这个代码。
<?php
// First we execute our common code to connection to the database and start the session
require("common.php");
// This if statement checks to determine whether the registration form has been submitted
// If it has, then the registration code is run, otherwise the form is displayed
if(!empty($_POST))
{
// Ensure that the user has entered a non-empty username
if(empty($_POST['email']))
{
// Note that die() is generally a terrible way of handling user errors
// like this. It is much better to display the error with the form
// and allow the user to correct their mistake. However, that is an
// exercise for you to implement yourself.
die("Please enter an email.");
}
// Make sure the user entered a valid E-Mail address
// filter_var is a useful PHP function for validating form input, see:
// http://us.php.net/manual/en/function.filter-var.php
// http://us.php.net/manual/en/filter.filters.php
if(!filter_var($_POST['email'], FILTER_VALIDATE_EMAIL))
{
die("Invalid E-Mail Address");
}
// Now we perform the same type of check for the email address, in order
// to ensure that it is unique.
$query = "
SELECT
1
FROM users
WHERE
email = :email
";
$query_params = array(
':email' => $_POST['email']
);
try
{
$stmt = $db->prepare($query);
$result = $stmt->execute($query_params);
}
catch(PDOException $ex)
{
die("Failed to run query: ");
}
$row = $stmt->fetch();
if($row)
{
die("This email address is already registered");
}
// An INSERT query is used to add new rows to a database table.
// Again, we are using special tokens (technically called parameters) to
// protect against SQL injection attacks.
$query = "
INSERT INTO users (
email
) VALUES (
:email
)
";
// This redirects the user back to the login page after they register
header("Location: login.php");
// Calling die or exit after performing a redirect using the header function
// is critical. The rest of your PHP script will continue to execute and
// will be sent to the user if you do not die or exit.
die("Redirecting to login.php");
}
?>
<h1>Register</h1>
<form action="register.php" method="post">
E-Mail:<br />
<input type="text" name="email" value="" />
<br /><br />
<input type="submit" value="Register" />
</form>
问题可能是由于这段代码造成的:
INSERT INTO users (
email
) VALUES (
:email
)
这是导致我在 phpMyAdmin 中出现问题的代码。它给了我这个错误:
#1064 - You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near ':email
)' at line 4
register.php 页面已成功连接到我的数据库,并且也在按预期重定向我,所以我觉得问题出在添加用户上。
问题是 mysql 不知道是什么:电子邮件是...尝试...
$email = mysql_real_escape_string($_POST['email']);
$query = "
INSERT INTO users (
email
) VALUES (
'$email'
)
";
使用
":email"
这可能有用...
您的 INSERT 语句似乎没有执行查询或分配电子邮件参数。
低于
$query = "
INSERT INTO users (
email
) VALUES (
:email
)
";
添加
$query_params = array(
':email' => $_POST['email']
);
try
{
$stmt = $db->prepare($query);
$result = $stmt->execute($query_params);
}
catch(PDOException $ex)
{
die("Failed to run query: ");
}
我 added/adjusted 你的代码。我使用了不同的占位符名称来简化调试
<?php
// First we execute our common code to connection to the database and start the session
require("common.php");
// This if statement checks to determine whether the registration form has been submitted
// If it has, then the registration code is run, otherwise the form is displayed
if(!empty($_POST))
{
// Ensure that the user has entered a non-empty username
if(empty($_POST['email']))
{
// Note that die() is generally a terrible way of handling user errors
// like this. It is much better to display the error with the form
// and allow the user to correct their mistake. However, that is an
// exercise for you to implement yourself.
die("Please enter an email.");
}
// Make sure the user entered a valid E-Mail address
// filter_var is a useful PHP function for validating form input, see:
// http://us.php.net/manual/en/function.filter-var.php
// http://us.php.net/manual/en/filter.filters.php
if(!filter_var($_POST['email'], FILTER_VALIDATE_EMAIL))
{
die("Invalid E-Mail Address");
}
// Now we perform the same type of check for the email address, in order
// to ensure that it is unique.
$checkSQL = <<<SQL1
SELECT
1
FROM users
WHERE
email = :checkemail
SQL1;
$insertSQL = <<<SQL2
INSERT INTO users (
email
) VALUES (
:insertemail
)
SQL2;
try
{
$s_ps = $db->prepare($checkSQL);
$s_ps -> bindValue(':checkemail',$_POST['email'],PDO::PARAM_STR);
$s_ps -> execute();
$checkRow = $s_ps->fetch();
if($checkRow)
{
die("This email address is already registered");
}
// An INSERT query is used to add new rows to a database table.
// Again, we are using special tokens (technically called parameters) to
// protect against SQL injection attacks.
$i_ps=$db -> prepare($insertSQL);
$i_ps -> bindValue(':insertemail',$_POST['email'],PDO::PARAM_STR);
$i_ps -> execute();
}
catch(PDOException $ex)
{
die("Failed to run query: ".$ex->getMessage());
}
// This redirects the user back to the login page after they register
header("Location: login.php");
// Calling die or exit after performing a redirect using the header function
// is critical. The rest of your PHP script will continue to execute and
// will be sent to the user if you do not die or exit.
die("Redirecting to login.php");
}
?>
<h1>Register</h1>
<form action="register.php" method="post">
E-Mail:<br />
<input type="text" name="email" value="" />
<br /><br />
<input type="submit" value="Register" />
</form>