Mysqli 访问被拒绝,使用 UNIX 套接字

Mysqli 访问被拒绝,使用 UNIX 套接字

我正在尝试学习 PHP,并且正在设置数据库连接。
在 Mysql Workbench 上,我创建了一个名为 php 的数据库,并创建了一个表。然后我使用 auth_socket 创建了帐户“sam”@“localhost”(我使用的是 Ubuntu 桌面,是sam的输出whoami),并授予了所有权限,当我按下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"

我没有sammysql 用户的密码。

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'

相关内容