Mysql

Mysqli 訪問被拒絕,使用 UNIX 套接字

  • August 16, 2021

我正在嘗試學習 PHP,並且正在設置數據庫連接。

在 Mysql Workbench 上,我創建了一個名為 php 的數據庫,並創建了一個表。然後我使用 auth_socket 創建了帳戶“sam”@“localhost”,(我使用的是 Ubuntu 桌面,並且sam是 的輸出whoami),Granted ALL on ,當我按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-&gt;host_info . "\n";

輸出在瀏覽器中什麼都沒有。

然後我嘗試了這個。

&lt;html&gt;
  &lt;head&gt;
     &lt;title&gt;Connecting MySQL Server&lt;/title&gt;
  &lt;/head&gt;
  &lt;body&gt;
     &lt;?php
        $dbhost = 'localhost';
        $dbuser = 'sam';
        //$dbpass = 'root@123';
        $mysqli = new mysqli($dbhost, $dbuser,NULL,NULL,NULL,"/run/mysqld/mysqld.sock");
        
        if($mysqli-&gt;connect_errno ) {
           printf("Connect failed: %s&lt;br /&gt;", $mysqli-&gt;connect_error);
           exit();
        }
        printf('Connected successfully.&lt;br /&gt;');
        $mysqli-&gt;close();
     ?&gt;
  &lt;/body&gt;
&lt;/html&gt;

輸出是 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]&gt; 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沒有密碼。

使用您的 Mysql Workbench 為使用者設置密碼,sam並使用該密碼連接 mysqli 庫。我不知道 Mysql Workbench 是否有點擊選項,如果沒有,或者您更喜歡 SQL 方式,請使用以下內容:

CREATE USER 'sam'@'localhost' IDENTIFIED BY 'choose_a_safe_password'

引用自:https://serverfault.com/questions/1074438