我是新手使用这个pdo来访问数据库。我正在尝试从数据库中获取ID,但我没有收到任何数据。
1:
$date = array(
':user' => $_POST['user'],
':pass' => $_POST['pass'],
);
$user->login($date);
2
function login ($date) {
$this->dbh->query("Select id From users Where username = ':user' and password = ':pass'");
$result = $this->dbh->execute_array($date);
$_SESSION['userid'] = $result['id'];
//header("Location: game.php");
}
3
function query($query) {
$this->stmt = $this->db->prepare($query);
}
function execute_array ($array) {
return $this->stmt->execute($array);
}
编辑:
我再次写了pdo代码,做了一些改变来解决我的问题。
function login ($date) {
$this->dbh->query("Select id From users Where username = :user and password = :pass");
$this->dbh->execute_array($date);
$result = $this->dbh->single();
$_SESSION['userid'] = $result['id'];
//header("Location: game.php");
}
function execute_array ($array) {
$this->stmt->execute($array);
}
function single() {
return $this->stmt->fetch(PDO::FETCH_ASSOC);
}
帮助我解决这个问题。
答案 0 :(得分:1)
你有sql语法错误:
[..snip..] username = ':user' and password = ':pass'
^-----^----------------^-----^---here
占位符不需要引用。数据库负责所有这些。
另外,您的execute_array()
方法可能会返回一个语句HANDLE。这不是您的查询的实际结果,而只是您可以用来获得这些结果的东西。
你可能想要更像
的东西 $result = $this->dbh->execute_array(...);
$row = $result->fetch();
$_SESSION['userid'] = $row['id'];
答案 1 :(得分:0)
你更喜欢这样:
try{
$this->db= new PDO(DBHost, DBName, DBUser, DBPassword, array(PDO::ATTR_PERSISTENT => true));
$this->db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$this->db->exec("SET CHARACTER SET utf8");
$sql="Select id From users Where username = :user and password = :pass";
$this->stmt = $pdo->prepare($sql, array(PDO::ATTR_CURSOR => PDO::CURSOR_SCROLL));
$this->stmt-> bindParam(':user', $date['user'], PDO::PARAM_STR);
$this->stmt-> bindParam(':pass', $date['pass'], PDO::PARAM_STR);
$this->stmt->execute();
if ($row = $stmt->fetch(PDO::FETCH_NAMED, PDO::FETCH_ORI_NEXT)) {
return $row['id'];
}else{
return NULL;
}
}catch(PDOException $e){
//TODO....
}