从过程MySQLi接口转移到基于对象

时间:2017-10-30 22:09:47

标签: php mysql mysqli

这是连接数据库的正确方法吗?

<?php

class Connect {

private $servername;
private $serveruser;
private $password;
private $database;

    function __construct($servername, $serveruser, $password, $database )
    {
        $this->servername = $servername;
        $this->serveruser = $serveruser;
        $this->password = $password;
        $this->database = $database;
    }

    function conn()
    {

        try {
        $conn = new mysqli($servername, $serveruser, $password, $database);
        echo "conn success";
        } 
        catch(Exception $e)
        {
        echo "ERROR: " . $e->getMessage();    
        }
    }

}
?>

如果我需要访问其他.php文件中的$ conn,我将如何操作?程序方法示例:$username = mysqli_real_escape_string($conn,$_POST['username']);如果我们使用OOP方法,这个字符串应该是什么样子?

P.S。请不要告诉我有关PDO的任何信息。

2 个答案:

答案 0 :(得分:0)

这就是你的代码实际上应该是这样的。

<xsl:template match="section[@type='index']">
    <xsl:if test="contains(.,comment())">
        <xsl:copy>
            <xsl:value-of select="." disable-output-escaping="yes"/>
        </xsl:copy>    
    </xsl:if>
</xsl:template>

答案 1 :(得分:-2)

使用现有代码,我认为这可能是维护连接实例的唯一方法。我的意思是,如果你不想每次都做(new Connect(...))->conn()

<?php

class Connect
{
    private $servername;
    private $serveruser;
    private $password;
    private $database;

    private static $conn = null;

    function __construct($servername, $serveruser, $password, $database )
    {
        $this->servername = $servername;
        $this->serveruser = $serveruser;
        $this->password = $password;
        $this->database = $database;
    }

    function conn()
    {

        try {
        $conn = new mysqli($servername, $serveruser, $password, $database);
        self::$conn = $conn;

        echo "conn success";
        } 
        catch(Exception $e)
        {
        echo "ERROR: " . $e->getMessage();    
        }
    }

    public static function instance()
    {
        if (! self::$conn)
        {
            # Initialize
            # (new static(...))->conn();
        }
        return self::$conn;
    }

}

# In your other *.php files
$username = mysqli_real_escape_string(Connect::instance(),$_POST['username']);