使用PDO()设置MySQL会话变量

时间:2021-04-17 01:11:49

I am using PHP's PDO to access my MySQL DB. I typically create a singleton class for my connection. I would like to set a MySQL session variable when initiating the connection, and later on as well. See below for my failed attempts to set MySession1 and MySession2. How can I do this? Thanks

我正在使用PHP的PDO访问我的MySQL数据库。我通常为我的连接创建一个单例类。我想在启动连接时设置MySQL会话变量,稍后也是如此。我在尝试设置MySession1和MySession2失败时见下文。我怎样才能做到这一点?谢谢

EDIT. Just found out that it works if you only use one @. I was originally using two at-signs @@ which I thought the documentation at http://dev.mysql.com/doc/refman/5.0/en/using-system-variables.html required. How am I misinterpreting the documentation?

编辑。刚刚发现如果你只使用一个@它就可以了。我最初使用两个at-signs @@,我认为http://dev.mysql.com/doc/refman/5.0/en/using-system-variables.html上的文档是必需的。我怎么会误解文档?

class db {
    private static $instance = NULL;
    private function __construct() {}   //Make private
    private function __clone(){}   //Make private
    public static function db() //Get instance of DB
    {
        if (!self::$instance)
        {
            self::$instance = new PDO("mysql:host=localhost;dbname=myDB", 'myUsername', 'myPassword');
            self::$instance->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
            self::$instance->exec('SET @MySession1=123');
        }
        return self::$instance;
    }
}

db::db()->exec('SET @MySession2=321');

$stmt=db::db()->query('SELECT @MySession1 AS MySession1, @MySession2 AS MySession2');
$rs=$stmt->fetch(PDO::FETCH_ASSOC);
echo("MySession1={$rs['MySession1']} MySession2={$rs['MySession2']}");

1 个解决方案

#1


0  

There is a difference between server variables and user defined variables. See http://dev.mysql.com/doc/refman/5.0/en/user-variables.html for the description of user defined variables.

服务器变量和用户定义的变量之间存在差异。有关用户定义变量的说明,请参见http://dev.mysql.com/doc/refman/5.0/en/user-variables.html。

#1


0  

There is a difference between server variables and user defined variables. See http://dev.mysql.com/doc/refman/5.0/en/user-variables.html for the description of user defined variables.

服务器变量和用户定义的变量之间存在差异。有关用户定义变量的说明,请参见http://dev.mysql.com/doc/refman/5.0/en/user-variables.html。