我正在使用PDO登录页面。
我无法登录,因为它显示“致命错误:在第13行的.. .loginc.php中调用boolean上的成员函数rowCount()”
我的连接页面:config.php
<?php
$host = '127.0.0.1';
$db = 'pan';
$user = 'root';
$pass = '';
$charset = 'utf8mb4';
$dsn = "mysql:host=$host;dbname=$db;charset=$charset";
$options = [
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,
PDO::ATTR_EMULATE_PREPARES => false,
];
try {
$pdo = new PDO($dsn, $user, $pass, $options);
} catch (\PDOException $e) {
throw new \PDOException($e->getMessage(), (int)$e->getCode());
}
?>
我的login.php页面如下:
<?php
session_start();
include('../../config/config.php');
extract($_POST);
$un=$_POST['un'];
$pw=$_POST['pw'];
$q=$pdo->prepare("select * from `admin` where userid=? and pass=?")->execute([$un,$pw])->rowCount();
if($q==1)
{
$_SESSION['login_as']="admin";
header("location:home_page.php");
}
else
{
$_SESSION['e']="Sorry...! Your username or password is incorrect.";
header('location:../index.php');
}
?>
我无法理解错误信息来自哪里我做错了。
PDOStatement::execute的结果是布尔值。你的错误的原因是$pdo->prepare("select * from
adminwhere userid=? and pass=?")->execute([$un,$pw])
返回布尔值,但你试图在这个布尔值上调用rowCount()
。
尝试使用下一个代码:
<?php
session_start();
include('../../config/config.php');
extract($_POST);
$un = $_POST['un'];
$pw = $_POST['pw'];
try {
$stmt = $pdo->prepare("select * from `admin` where userid=? and pass=?");
$stmt->execute([$un, $pw]);
/* Or replace $stmt->execute([$un, $pw]); with next lines:
$stmt->bindParam(1, $un);
$stmt->bindParam(2, $pw);
$stmt->execute();
*/
$q = $stmt->rowCount();
if ($q == 1) {
$_SESSION['login_as']="admin";
header("location:home_page.php");
} else {
$_SESSION['e']="Sorry...! Your username or password is incorrect.";
header('location:../index.php');
}
} catch (\PDOException $e) {
throw new \PDOException($e->getMessage(), (int)$e->getCode());
}
?>
$q = $pdo->prepare("select * from `admin` where userid= ? and pass= ? ");
$q->execute(array($un,$pw));
$q->rowCount();
基于PHP文档(PDOStatement::rowCount),最好使用query()和fetchColumn(),因为:
对于大多数数据库,PDOStatement :: rowCount()不返回受SELECT语句影响的行数。
这是PHP文档中的一个示例:
<?php
$sql = "SELECT COUNT(*) FROM fruit WHERE calories > 100";
if ($res = $conn->query($sql)) {
/* Check the number of rows that match the SELECT statement */
if ($res->fetchColumn() > 0) {
/* Issue the real SELECT statement and work with the results */
$sql = "SELECT name FROM fruit WHERE calories > 100";
foreach ($conn->query($sql) as $row) {
print "Name: " . $row['NAME'] . "\n";
}
}
/* No rows matched -- do something else */
else {
print "No rows matched the query.";
}
}
$res = null;
$conn = null;
?>
希望这可以帮助!