doupo1890 2016-03-23 23:36
浏览 104

在Ubuntu 14上使用PHP连接到MySQL

I am trying to connect to a MySQL database using PHP using the following code:

<?php
$servername = "localhost";
$username = "root";
$password = "pass";

// Create connection
$conn = new mysqli($servername, $username, $password);

// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
} 
echo "Connected successfully";
?>

When using localhost, I get a message

Connection failed: No such file or directory

When using 127.0.0.1 for the host, I get

Connection failed: Connection refused

I have confirmed that I can connect using the command line, and the output is below

mysql -u root -p pass -h localhost
Enter password:
Welcome to the MySQL monitor.  Commands end with ; or \g.
Your MySQL connection id is 7282
Server version: 5.5.47-0ubuntu0.14.04.1-log (Ubuntu)

Connecting using TCP

mysql -u root -p pass -h 127.0.0.1
Enter password:
Welcome to the MySQL monitor.  Commands end with ; or \g.
Your MySQL connection id is 7318
Server version: 5.5.47-0ubuntu0.14.04.1-log (Ubuntu)

The following is the relevant mysqli section of the php.ini file in /etc/php5/apache2

mysqli.default_port = 3306
mysqli.default_socket = /var/run/mysqld/mysqld.sock
mysqli.default_host = 127.0.0.1

And the settings from /etc/mysql/my.cnf

[mysqld]
#
# * Basic Settings
#
user        = mysql
pid-file    = /var/run/mysqld/mysqld.pid
socket      = /var/run/mysqld/mysqld.sock
port        = 3306
.
.
.
bind-address        = 127.0.0.1

I have tried using PDO to connect to the database with the same results. Can anyone see a configuration setting that is not correct, or have another idea of what could be wrong?

Edit: I installed phpmyadmin and it connects to MySQL with the same settings.

  • 写回答

1条回答 默认 最新

  • dqg2269 2016-03-23 23:50
    关注

    Try to do this?

    <?php
    $servername = "localhost";
    $username = "username";
    $password = "password";
    
    // Create connection
    $conn = new mysqli($servername, $username, $password);
    
    // Check connection
    if ($conn->connect_error) {
        die("Connection failed: " . $conn->connect_error);
    } 
    echo "Connected successfully";
    ?>
    
    评论

报告相同问题?

悬赏问题

  • ¥15 java 操作 elasticsearch 8.1 实现 索引的重建
  • ¥15 数据可视化Python
  • ¥15 要给毕业设计添加扫码登录的功能!!有偿
  • ¥15 kafka 分区副本增加会导致消息丢失或者不可用吗?
  • ¥15 微信公众号自制会员卡没有收款渠道啊
  • ¥15 stable diffusion
  • ¥100 Jenkins自动化部署—悬赏100元
  • ¥15 关于#python#的问题:求帮写python代码
  • ¥20 MATLAB画图图形出现上下震荡的线条
  • ¥15 关于#windows#的问题:怎么用WIN 11系统的电脑 克隆WIN NT3.51-4.0系统的硬盘