检查用户名是否存在:在非对象上调用成员函数rowCount()

时间:2013-12-08 22:30:22

标签: php mysql

我正在尝试检查数据库中是否存在现有用户,并且在尝试检查数据库中的用户名时,我一直收到此错误。

Call to a member function rowCount() on a non-object

^这是错误

这是register.php的顶部:

<?php
session_start();
require("database.class.php");
$dbn = new database(); // Define a new instance of the class "database".
$dbn->init("localhost", "root", "", "mrl-lr"); // Run the init function inside of "database" to set database connection parameters.
$db = $dbn->connect(); // Finally, run the connection and get a fully functional database connection!

&GT;

以下是register.php中的USERNAME代码:

// Step 5) Check if the username has not been entered.
if (!isset($_POST['username']) or empty($_POST['username'])) // ! = not; if not isset $_POST['username'] or empty $_POST['username'] then
{
    // Step 5, 1) Log an error about the username not being entered.
    $errors[] = "Username has not been entered!"; // [] is called "pushing" - pushing puts items into an array(in our case, errors).
} else {
    // Step 5, 2) Check other validations.
    // Step 5, 2, 1) RegEx Checking
    if (!preg_match("/^[a-zA-Z0-9\s-\pL]+$/u", $_POST['username']))
    {
        $errors[] = "Username may only be numbers, letters and -'s!";
    }
    // Step 5, 2, 2) Check to see if the username is less than 4 chars or more than 46.
    if (strlen($_POST['username']) <= 4 or strlen($_POST['username']) >= 46) 
    {
        $errors[] = "Username must be 5-45 characters long.";
    }
    $count = $db->prepare("SELECT * FROM `users` WHERE `username`=?");
    $user =  strip_tags(addslashes($_POST['username']));
    $count->bindParam(1, $user, PDO::PARAM_STR);
    $count = $count->execute();

    if ($count->rowCount() == 1)
    {
        $errors[] = "Time to be original! That user already exists!";
    }
}

这是来自database.class.php的代码

<?php
class database
{

    protected $host = "";
    protected $user = "";
    protected $pass = "";
    protected $dbname = "";

    public function init($host, $user, $pass, $dbname)
    {
        $this->host = $host;
        $this->user = $user;
        $this->pass = $pass;
        $this->dbname = $dbname;
    }

    public function connect()
    {
        $connection = new PDO("mysql:host=".$this->host.";dbname=".$this->dbname, $this->user, $this->pass);
        return ($connection ? $connection : false);
    }

    public function hashit($string, $salt)
    {
        return hash("whirlpool", $salt.$string.$salt);
    }

}

&GT;

2 个答案:

答案 0 :(得分:1)

您不应该在此行中重新分配$count变量:

$count = $count->execute();

相反它应该是这样的:

$res = $count->execute();

Explenation:execute()方法返回一个布尔值,指示执行是否成功。在您的代码中,您将使用该布尔值覆盖$count语句。

答案 1 :(得分:0)

您的问题是您没有从数据库中获得任何结果,因此您无法检索行计数。你需要做的是更像这样的事情:

$stmt=$db->prepare("SELECT * FROM Document");
$stmt->execute();

if ($row = $page->fetch(PDO::FETCH_ASSOC)) {
    // logic for true
}

您可以阅读有关PDO fetch here

的信息

编辑:顺便说一下,准备好的语句应该剥离标签并为你添加斜杠。那部分是多余的。

此外,您将错误定义为数组,但是您将继续覆盖整个数组而不是添加它。试试array_push