来自PDO手册:
PDOStatement::rowCount() returns the number of rows affected by the last DELETE, INSERT, or UPDATE statement executed by the corresponding PDOStatement object.
If the last SQL statement executed by the associated PDOStatement was a SELECT statement, some databases may return the number of rows returned by that statement. However, this behaviour is not guaranteed for all databases and should not be relied on for portable applications.
我有这段代码:
<?php
require 'core.inc.php';
if(isset($_POST['user']) AND isset($_POST['pass'])){
if(!empty($_POST['user']) AND !empty($_POST['pass'])){
$user = $_POST['user'];
$pass = $_POST['pass'];
require 'connect.inc.php';
$st = $db_pdo->prepare("SELECT id FROM users WHERE user=? AND pass=?");
$st->bindParam(1, $user);
$st->bindParam(2, $pass);
$st->execute();
$result = $st->fetchColumn();
if($st->rowCount() > 0){
$id_arr = $st->fetch();
$id = $id_arr[0];
$_SESSION['user_id'] = $id;
header('Location: edit.php');
} else { echo 'Username or password incorrect';}
} else { echo 'You must fill in all fields.';}
}
?>
返回的行数始终为0,如手册中所述。这并不奇怪。
1)我想记录一个用户并将他的$ _SESSION id设置为来自db的用户ID。
2)我非常喜欢PDO它甚至不好笑,我无法弄清楚用什么函数来记录用户。如果数字或行总是0,显然用户名或密码不正确将显示全部时间。
答案 0 :(得分:0)
试试这个:
try
{
$pdo_options[PDO::ATTR_ERRMODE] = PDO::ERRMODE_EXCEPTION;
$bdd = new PDO('mysql:host='.$host.';dbname=' . $dbname, $dbuser, $dbpassword, $pdo_options);
$request = $bdd->prepare('SELECT id FROM users WHERE user = :user AND pass = :password');
$request->execute(array('user' => $_POST['user'],
'password' => $_POST['pass']
));
$data = $request->fetch();
if ($data)
{
session_start();
$_SESSION['ID'] = $data['id'];
//you can run other verification here if you want
header('Location: edit.php');
}
else
{
echo 'Username or password incorrect';
}
$requete->closeCursor();
}
catch(Exception $erreur)
{
die('Login error : '.$erreur->getMessage());
}
希望有所帮助。