I am studying PHP on a local server (PHP 7.0.14) in MacOS 10.12.2.
<?php
define('DB_DATABASE', 'test_db'); // database specification
define('DB_USERNAME', 'dbuser'); // database user
define('DB_PASSWORD', '******'); // database password
define('PDO_DSN', 'mysql:dbhost=localhost;dbname='.DB_DATABASE);
// String to connect to the database
try{
// connect
$db = new PDO(PDO_DSN, DB_USERNAME, DB_PASSWORD);
$db->setAttribute(PDO::ATTR_ERRMODE,PDO::ERRMODE_EXCEPTION);
// insert
$db->exec("insert into users(name,core) values('ryo','55')";
echo "user added!";
//disconnect
$db = null;
}catch(PDOException$e){
echo$e->getMessage();
exit;
}
If you access this index.php, the simple code is to add information to the database.
When connected through a browser, SQLSTATE [HY000] [2002] No such file or directory error appears.
sudochmod777/usr/local/var/mysql/
I also gave PHP access to the database by running , but it didn't work.
Please reply.
php mysql macos
I got the same error.
MySQL was not started.
$sudo mysql.server start
It was cool.
Note: Unix only
If the hostname is "localhost"
, the connection to the server is made using a domain socket.
If you compiled PDO_MYSQL using libmysqlclient, the socket file is located at the time of the libmysqlclient compilation.
If you compiled PDO_MYSQL using mysqlnd, the default socket is created using the pdo_mysql.default_socket
setting.
-- http://php.net/manual/ja/ref.pdo-mysql.connection.php
If the above quoted event is occurring, No such file or directory
means that the socket file cannot be found.
After starting mysqld
, identify the path to the socket file and specify it in php.ini, or
You can specify a socket connection simply by unix_socket=...
for PDO_DSN
.
(/usr/local/var/mysql
) If you installed MySQL on Homebrew, I think the socket file location would have been /tmp/mysql.sock
.
Alternatively, host=127.0.0.1
may prevent you from falling into the above limitations (not confirmed).
Please check it out.
One more thing
The PDO_MYSQL data source name (DSN) consists of the following elements:
...
host
Specifies the hostname where the database server resides.
-- http://php.net/manual/ja/ref.pdo-mysql.connection.php
Therefore, I think host=localhost
is correct instead of dbhost=localhost
.
(Well, it seems that the socket will be connected if it is correct...)
© 2024 OneMinuteCode. All rights reserved.