0

我在线关注的教程让我创建了两个不同的 PHP 文件。这是 Database.php 文件:

<?php
class dbConnection
{
    protected $db_connection;
    public $db_name = "todo";
    public $db_user = "root";
    public $db_password = "";
    public $db_host = "localhost";

    function connect()
    {
        try
        {
            $this -> db_connection = new PDO("mysql:host=$this->db_host;dbname=$this->db_name", $this -> db_user, $this -> db_password);

            return $this -> db_connection;
        }

        catch(PDOException $e)
        {
            return $e -> getMessage();
        }
    }

}
?>

这是 ManageUsers.php 文件:

<?php
include_once ('Database.php');

class ManageUsers
{
    public $link;

    function __construct()
    {
        $dbConnection = new dbConnection();
        $this -> link = $dbConnection -> connect();

        return $this -> link;
    }

    function registerUsers($username, $password, $ip_address, $date, $time)
    {
        $query = $this->link->prepare('INSERT INTO users(username, password, ip_address, reg_date, reg_time) VALUES (?,?,?,?,?)');

        $values = array(
            $username,
            $password,
            $ip_address,
            $date,
            $time
        );

        $query -> execute($values);
        $rowCount = $query -> rowCount();

        return $rowCount;
    }

}

$users = new ManageUsers();

echo $users -> registerUsers("Bob", "Bob", "127.0.0.1", "07/08/2013", "9:34 A.M.");
?>

它在 prepare() 上一直失败,教程中没有任何内容告诉我原因。任何帮助将不胜感激。

4

2 回答 2

0

您的 connect() 函数将返回数据库对象或错误字符串。您需要在 connect() 中实际抛出错误而不返回它,或者检查 $this->link 是否是 __construct 中的字符串。构造函数无论如何都不应该返回值,否则您将值分配给变量而不是类实例。

于 2013-07-08T14:48:09.190 回答
0

可能,您的数据库连接出错,它返回一个字符串而不是一个PDO对象:

$this -> db_connection = 
   new PDO("mysql:host=$this->db_host;dbname=$this->db_name", 
       $this -> db_user, $this -> db_password);

你必须写得有点不同:

$this -> db_connection = 
   new PDO("mysql:host={$this->db_host};dbname={$this->db_name}", 
       $this -> db_user, $this -> db_password);

另外,请确保您正确处理错误(如果有的话,您会自己找到它)。

于 2013-07-08T14:46:40.410 回答