Switch between multiple database in PDO

后端 未结 5 867
陌清茗
陌清茗 2020-12-10 01:48

I\'m new to PDO. I would like to know if there is anything similar to mysql_select_db in PDO, so that i can switch between different databases during runtime without the nee

相关标签:
5条回答
  • 2020-12-10 02:28

    There is not, you will need to create two PDO objects for the separate connections if you would like to use both at runtime.

    Edit: Interesting point by @laz below (which I'm guessing is the cause of negative votes on my answer). I was thinking under the assumption that the databases were on separate servers tbh, in which case my answer stands.

    0 讨论(0)
  • 2020-12-10 02:33

    I know that I am a couple of months late but you should be able to switch between databases from within your query.

    examples:

    $sql = "SELECT * FROM dbname.tablename";
    
    $sql = "SELECT * FROM anotherdbname.anothertablename"
    

    So even if your original $pdo object was used 'blahblah' as the dbname, you should still be okay based on the select examples I provided.

    0 讨论(0)
  • 2020-12-10 02:36

    you don't even need to specify the database in every query, just use msyql syntax

     USE db_name
    

    and then write your requests

    0 讨论(0)
  • 2020-12-10 02:37

    It looks like PDO does not have database switching because not every database engine supports it.

    AFAIK PostgreSQL does not have database switching, but offer schemas and u can switch between those.

    However if you're using mysql check if this works for you:

    $pdo = new PDO('mysql:dbname=db1;host=127.0.0.1','user','pass');
    
    $sql = 'select count(*) from table_name';
    
    $res = $pdo->query($sql);
    print_r($res->fetchAll());
    
    $pdo->exec('USE db2');
    
    $res = $pdo->query($sql);
    print_r($res->fetchAll());
    
    0 讨论(0)
  • 2020-12-10 02:46

    You actually do not need to specify the database upon connection at all. As long as you specify the database in every query, as Laz stated, this will work:

    $dbh = new PDO('mysql:host=127.0.0.1','USER','PASS');
    
    $query = "SELECT * FROM database1.table1";
    $query = "SELECT * FROM database2.table1";
    
    0 讨论(0)
提交回复
热议问题