
私はPHPを学ぼうとしており、データベース接続を設定しています。Mysql
Workbenchで、phpというデータベースを作成し、テーブルを作成しました。次に、アカウント「sam」@「localhost」(Ubuntuデスクトップを使用しており、sam
の出力ですwhoami
)を作成し、auth_socketでALLを許可しました。。を押しctrl+alt+T
て入力しmysql
、 を押すとenter
正常にログインできます。
今、私はhttps://www.php.net/manual/en/mysqli.quickstart.connections.php、ソケットを使用しようとしましたが、失敗しました。
2021/08/13 16:54:35 [error] 1363#1363: *11 FastCGI sent in stderr: "PHP message: PHP Warning: mysqli::__construct(): (HY000/1698): Access denied for user 'sam'@'localhost' in /var/www/php/my2.php on line 3PHP message: PHP Warning: main(): Couldn't fetch mysqli in /var/www/php/my2.php on line 5" while reading response header from upstream, client: 127.0.0.1, server: _, request: "GET /my2.php HTTP/1.1", upstream: "fastcgi://unix:/var/run/php/php7.4-fpm.sock:", host: "localhost:803"
これが私のコードです。<?php
$mysqli = new mysqli("localhost", "sam", Null, "php");
echo $mysqli->host_info . "\n";
ブラウザでは何も出力されません。
それからこれを試してみました。
<html>
<head>
<title>Connecting MySQL Server</title>
</head>
<body>
<?php
$dbhost = 'localhost';
$dbuser = 'sam';
//$dbpass = 'root@123';
$mysqli = new mysqli($dbhost, $dbuser,NULL,NULL,NULL,"/run/mysqld/mysqld.sock");
if($mysqli->connect_errno ) {
printf("Connect failed: %s<br />", $mysqli->connect_error);
exit();
}
printf('Connected successfully.<br />');
$mysqli->close();
?>
</body>
</html>
出力はConnect failed: Access denied for user 'sam'@'localhost'
ログ付き
2021/08/13 16:59:17 [error] 1363#1363: *13 FastCGI sent in stderr: "PHP message: PHP Warning: mysqli::__construct(): (HY000/1698): Access denied for user 'sam'@'localhost' in /var/www/php/mysqli.php on line 10" while reading response header from upstream, client: 127.0.0.1, server: _, request: "GET /mysqli.php HTTP/1.1", upstream: "fastcgi://unix:/var/run/php/php7.4-fpm.sock:", host: "localhost:803"
mysql のユーザーのパスワードがありませんsam
。
MariaDB [mysql]> select user,password from user;
+-----------+-------------------------------------------+
| user | password |
+-----------+-------------------------------------------+
| root | |
| someone | *2470C0C06DEE42FD1618BB99005ADCA2EC9D1E19 |
| someone | *9B8A3238012965AC630589D859535EA0B7C231A7 |
| someone | *AF411B6C73B3AC3A2316A309A71758175CC14FEE |
| someone | *D76A454D84260E84578F09915624F275F3D0E08B |
| sam | |
+-----------+-------------------------------------------+
6 rows in set (0.001 sec)
sam
プライバシー保護のため、実際のユーザー名を誰かに変更しました。パスワードがないことがわかります。
答え1
Mysql Workbench を使用してユーザーのパスワードを設定しsam
、そのパスワードを使用して mysqli ライブラリに接続します。Mysql Workbench にクリックスルー オプションがあるかどうかはわかりませんが、ない場合、または SQL 方式を好む場合は、次のようなものを使用します。
CREATE USER 'sam'@'localhost' IDENTIFIED BY 'choose_a_safe_password'