- 我正在使用Wamp,
- myown pc作为localhost
- 端口:80
- 我已经将php脚本的文件保存在通常的默认位置
C:wampwwwwebservice
- 我为php访问创建了一个配置文件,我将其称为
config.inc.php
- 我已经用凭据
username=dev, password=root, databasename=webservice
创建了mysql数据库
代码如下:
<?php
// These variables define the connection information for your MySQL database
$username = "dev";
$password = "root";
$host = "localhost";
$dbname = "webservice";
$options = array(PDO::MYSQL_ATTR_INIT_COMMAND => 'SET NAMES utf8');
try
{
$db = new PDO("mysql:host={$host};dbname={$dbname};charset=utf8", $username, $password, $options);
}
catch(PDOException $ex)
{
die("Failed to connect to the database: " . $ex->getMessage());
}
$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$db->setAttribute(PDO::ATTR_DEFAULT_FETCH_MODE, PDO::FETCH_ASSOC);
if(function_exists('get_magic_quotes_gpc') && get_magic_quotes_gpc())
{
function undo_magic_quotes_gpc(&$array)
{
foreach($array as &$value)
{
if(is_array($value))
{
undo_magic_quotes_gpc($value);
}
else
{
$value = stripslashes($value);
}
}
}
undo_magic_quotes_gpc($_POST);
undo_magic_quotes_gpc($_GET);
undo_magic_quotes_gpc($_COOKIE);
}
header('Content-Type: text/html; charset=utf-8');
session_start();
?>
然后我使用名为register.php
的脚本文件创建了一个简单的功能测试
代码如下::
<?php
require ("config.inc.php");
?>
<h1>Register</h1>
<form action="register.php" method="post">
Username:<br/>
<input type="text" name="username" placeholder="user name"><br/>
Password:<br/>
<input type="password" name="username" placeholder="user name"><br/>
<input type="submit" value="Register user"/>
</form>
当我从浏览器http://localhost/webservice/register.php
运行时
我在浏览器中得到这个错误显示为
无法连接到数据库:SQLSTATE[2800][1045]拒绝用户"dev'@'localhost'"的访问(使用密码:YES)
请就如何克服提出任何建议
出于安全原因,请不要使用root。可能用户配置不好。也请查看此文档http://dev.mysql.com/doc/refman/5.1/en/create-user.html.
此外,我在您的代码中看到session_start()是在脚本结束时调用的,如果以前发生这样的错误,PHP将打印错误,而不会启动会话,因此您应该在脚本开始时使用它。
希望能有所帮助。