我的PHP代码有问题,我需要为我的数据库划分功能

时间:2017-01-19 15:09:58

标签: php mysql

我试图将函数划分为创建表并连接到数据库,但创建表的php函数对我不起作用,有没有人知道如何解决这个问题?我附上了php代码和索引。

prova.php:

class db_mysqls
{
    public function connect()
    {
        $username="username";
        $password="password";
        try
        {
            $connection = new PDO("mysql:host=localhost;dbname=ijdb",$username, $password);
            $connection->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
            echo ' <br> Connection Complete';
        }
        catch (PDOException $e)
        {
            echo 'Connection failed: ' . $e->getMessage();
        }
    }

    public function createDB()
    {
        try
        {
            $sql="CREATE TABLE joke (
                    id INT NOT NULL AUTO_INCREMENT PRIMARY KEY, 
                    joketext TEXT,
                    jokedate DATE NOT NULL)";
            // use exec() because no results are returned
            $connection->exec($sql);
            echo "Table MyGuests created successfully";
        }
        catch (PDOException $e)
        {
            echo 'Creation failed: ' . $e->getMessage();
        }
    }
}
?>

的index.php:

<html>
    <head>
        <title>Index.html</title>
    </head>
    <body>
        Eseguo prova.php <br>
        <?php
            include 'prova.php';
                $db = new db_mysqls();
                echo 'New Database Object Created';
                $db->connect();
                $db->createDB();
        ?>
    </body>
</html>

1 个答案:

答案 0 :(得分:2)

问题是可变范围。你所有的变量都是本地的。您需要创建一个私有类成员来存储连接对象,以便两种方法都可以访问相同的连接。

<?php
class db_mysqls
{
    private $connection; 

    public function connect()
    {
        $username="username";
        $password="password";
        try
        {
            $this->connection = new PDO("mysql:host=localhost;dbname=ijdb",$username, $password);
            $this->connection->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
            echo ' <br> Connection Complete';
        }
        catch (PDOException $e)
        {
            echo 'Connection failed: ' . $e->getMessage();
        }
    }

    public function createDB()
    {
        try
        {
            $sql="CREATE TABLE joke (
                    id INT NOT NULL AUTO_INCREMENT PRIMARY KEY, 
                    joketext TEXT,
                    jokedate DATE NOT NULL)";
            // use exec() because no results are returned
            $this->connection->exec($sql);
            echo "Table MyGuests created successfully";
        }
        catch (PDOException $e)
        {
            echo 'Creation failed: ' . $e->getMessage();
        }
    }
}
?>