致命错误:在第13行的.. .loginc.php中,对布尔值的成员函数rowCount()进行调用

时间:2019-02-27 03:30:45

标签: php pdo

我正在使用PDO登录页面。

我无法登录,因为它显示“ 致命错误:在第13行的.. .loginc.php中,对布尔值的成员函数rowCount()进行调用

我的连接页面:config.php

<form id="survey-form">
  <div class="row">
    <label for="name">* Name:</label>
    <input type="text" id="name" class="input-field" required placeholder="Enter your name">    
    </div>

  <div class="row">
    <label for="email">* Email:</label>
    <input type="email" id="email" class="input-field" required placeholder="Enter your email">    
  </div>
</form>

我的loginc.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());
}
?>

对于错误消息的出处,我无法理解我在哪里做错了。

3 个答案:

答案 0 :(得分:1)

$q = $pdo->prepare("select * from `admin` where userid= ? and pass= ? ");
$q->execute(array($un,$pw));
$q->rowCount();

答案 1 :(得分:0)

基于 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;
?>

希望这会有所帮助!

答案 2 :(得分:0)

PDOStatement::execute的结果为布尔值。 错误的原因是$pdo->prepare("select * from管理员where 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());
    }   
?>