我有一个数据库,它有两条记录用于测试目的......数据库列(user_id、用户名、密码和角色)......
我正在使用 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 中不是很好......谢谢你的时间