How do I select a MySQL database to use with PDO in PHP?

前端 未结 4 1544
独厮守ぢ
独厮守ぢ 2020-12-05 04:18

I want to select a MySQL database to use after a PHP PDO object has already been created. How do I do this?

// create PDO object and connect to MySQL
$dbh =         


        
4条回答
  •  陌清茗
    陌清茗 (楼主)
    2020-12-05 04:58

    Alternatively, you can select a MySQL database to use after a PHP PDO object has already been created as below:

    With USE STATEMENT. But remember here USE STATEMENT is mysql command

    try
    {
        $conn = new PDO("mysql:host=$servername;", $username, $password);
        // set the PDO error mode to exception
        $conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
    
        $conn->exec("use databasename");
        //application logic
    }
    catch(PDOException $e)
    {
        echo $sql . "
    " . $e->getMessage(); } $conn = null;

    I hope my code is helpful for requested

提交回复
热议问题