我有一个数据库,其中有两个记录用于测试目的…数据库列(user_id, username, password, role)....
我正在使用PHP PDO与数据库通信,我已经创建了一个类文件,扩展PDO下面
<?php
require_once('constants.php');
class PDOConfig extends PDO{
private $real_escape_string;
private $mageic_quote_active;
public function __construct(){
$dsn = DBENGINE .':dbname='. DBNAME.";host=".DBHOST;
parent::__construct($dsn, DBUSER, DBPW);
$mageic_quote_active = get_magic_quotes_gpc();
$real_escape_string = function_exists("mysql_real_escape_string");
}
public function escapeValue($value){
//PHP >= 4.3.0 or greater
if($this->real_escape_string){
if($this->mageic_quote_active){
//if new version exists turn magic quotes off
$value = stripslashes($value);
}
$value = mysql_real_escape_string($value);
}
return $value;
}
}//end of class
$connection = new PDOConfig();
$database =& $connection;
我在我的登录页面上使用这个文件,它有以下代码
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Sign In</title>
<link rel="stylesheet" href="css/bootstrap.css">
<link rel="stylesheet" href="css/singin-form.css">
<?php require_once('includes/PDOConfig-class.php'); ?>
<?php //require_once('includes/utility-functions.php'); ?>
<?php
$errors = "";
if(isset($_POST['submit'])){
$username = trim($_POST['username']);
$password = trim($_POST['password']);
if(!empty($username) && !empty($password)){
$sql = "SELECT * FROM user WHERE user_name = '" . $database->escapeValue($username) . "'";
$prestmt = $database->prepare($sql);
$prestmt->execute();
$result = $prestmt->fetch($database::FETCH_ASSOC);
//print_r($result);
echo $result['role'];
echo "<br /> Query : " . $sql;
}
//echo '<div class="alert alert-error">something wrong<button type="button" class="close" data-dismiss="alert">×</button></div>';
}
?>
</head>
<body>
<div class="container">
<form class="form-signin" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]); ?>" method="post">
<h2>Please sign in</h2>
<input type="text" name="username" class="input-block-level" placeholder="User Name" />
<input type="password" name="password" class="input-block-level" placeholder="Password" />
<button name="submit" class="btn btn-primary btn-large" type="submit">Login</button>
</form>
</div>
</body>
</html>
但是我在我的页面上没有看到任何东西,除了我打印的查询…尽管那里有数据在那里的数据库…
另一件事当我尝试使用"FETCH_OBJ"时,我得到以下错误
trying to get property of non-object in C:'wamp'www'testPHP'login.php on line 30
生成上述错误的代码在
下面if(!empty($username) && !empty($password)){
$sql = "SELECT * FROM user WHERE user_name = '" . $database->escapeValue($username) . "'";
$prestmt = $database->prepare($sql);
$prestmt->execute();
$result = $prestmt->fetch($database::FETCH_OBJ);
echo $result->role;
}
请帮助,因为我从来没有使用过PHP PDO和不是很好在PHP…感谢您的宝贵时间
这个链接包含了你需要的一切
- 连接到db的方式描述(使PDO通知你的错误)
- 按照上面描述的方式为查询分配变量(以使您的查询安全合理) 摆脱你的PDOConfig,因为它完全没用。你只需要构造函数,所以,你可以把构造函数代码本身放入PDOConfig-class.php
然后运行你的代码,看看哪里出错了