简体   繁体   中英

PDO MySQL Connection Issue from command line

I have a php script I want to run in the background from the terminal on MacOs. I'm having trouble connecting to the database, however the exact same script has no problems when it's run from the browser.

Heres the script:

<?php

echo "START";

try { 
    $con = new PDO("mysql:host=localhost;dbname=issues;charset=utf8", "root", "root"); 
    $con->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); 
    $con->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);
} 
catch(PDOException $e) { 
    throw new Exception($e->getMessage());
}

echo "here"; ?>

I'm running it from the terminal with php script.php

The error with the try catch block I get is:

START

Fatal error: Uncaught exception 'Exception' with message 'SQLSTATE[HY000] [2002] No such file or directory' in /Applications/MAMP/htdocs/issueManager3/notifications.php:11 Stack trace: #0 {main} thrown in /Applications/MAMP/htdocs/issueManager3/notifications.php on line 11

The error I get without the try catch block is: START Fatal error: Uncaught exception 'PDOException' with message 'SQLSTATE[HY000] [2002] No such file or directory' in /Applications/MAMP/htdocs/issueManager3/notifications.php:6 Stack trace:#0 /Applications/MAMP/htdocs/issueManager3/notifications.php(6): PDO->__construct('mysql:host=loca...', 'root', 'root')#1 {main} thrown in /Applications/MAMP/htdocs/issueManager3/notifications.php on line 6

It's saying no such file or directory, but it's echoing out "START" so its definitely not a case of not being able to find the script. Am I missing something I need to add in the connect to a database when the script is being executed from the terminal?

Any help appreciated.

Try this code:

   <?php

    echo "START";

    try { 
        $con = new PDO("mysql:host=127.0.0.1;dbname=issues;charset=utf8", "root", "root"); 
        $con->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); 
        $con->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);
    } 
    catch(PDOException $e) 
{ 
       echo $e->getMessage();
    }

    echo "here"; ?>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM