【问题标题】:Laravel 8.0.3 - Can't get data from the databaseLaravel 8.0.3 - 无法从数据库中获取数据
【发布时间】:2020-12-28 23:37:37
【问题描述】:

我正在尝试从posts 表中获取数据,但我收到一条错误消息:

PostsController.php

namespace App\Http\Controllers;
use Illuminate\Support\Facades\DB;
use Illuminate\Http\Request;

class PostsController extends Controller
{
    public function show( $slug ) {        
        $posts = DB::table('posts')->get();
        dd($posts);
    }
}

.env 文件

DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=laravel
DB_USERNAME=root
DB_PASSWORD=root

但我收到此错误:

SQLSTATE[HY000] [2002] 连接被拒绝(SQL: select * from posts

我尝试访问的网址:

http://127.0.0.1:8000/posts/first-post

查看可分享的 laravel 错误消息:

https://flareapp.io/share/xPQr0171#F54

更新:

运行php artisan migrate后收到的错误消息

 SQLSTATE[HY000] [2002] Connection refused (SQL: select * from information_schema.tables where table_schema = laravel and table_name = migrations and table_type = 'BASE TABLE')

  at vendor/laravel/framework/src/Illuminate/Database/Connection.php:671
    667▕         // If an exception occurs when attempting to run a query, we'll format the error
    668▕         // message to include the bindings with SQL, which will make this exception a
    669▕         // lot more helpful to the developer instead of just the database's errors.
    670▕         catch (Exception $e) {
  ➜ 671▕             throw new QueryException(
    672▕                 $query, $this->prepareBindings($bindings), $e
    673▕             );
    674▕         }
    675▕ 

      +37 vendor frames 
  38  artisan:37
      Illuminate\Foundation\Console\Kernel::handle(Object(Symfony\Component\Console\Input\ArgvInput), Object(Symfony\Component\Console\Output\ConsoleOutput))

原始代码

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

try {
  $conn = new PDO("mysql:host=$servername;dbname=laravel", $username, $password);
  // set the PDO error mode to exception
  $conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
  echo "Connected successfully";
} catch(PDOException $e) {
  echo "Connection failed: " . $e->getMessage();
}

【问题讨论】:

  • 如果您使用 PhpMyAdmin 或 HeidiSQL 或 MySqlWorkbenck 或其他任何方式尝试使用您的凭据,它们是否有效?
  • 我已经检查了与原始代码的连接。它在那里工作。
  • 为什么人们提供负面标记???我是 laravel 的新手。
  • 您是否在 PHP 中启用了正确的 PDO 扩展?
  • 是的,我已经启用了。

标签: php laravel


【解决方案1】:

你能测试一下吗:

namespace App\Http\Controllers;
use Illuminate\Support\Facades\DB;
use Illuminate\Http\Request;

class PostsController extends Controller
{
    public function show( $slug ) {
        return response()->json(
            config("database.connections.mysql.database"),
            200
        );
    }
}

它应该显示您的数据库名称 (laravel)。
如果不是,您的.env 文件无效。

【讨论】:

  • 我已经解决了这些问题。都是关于 MySQL 端口问题
猜你喜欢
  • 2021-07-02
  • 2017-09-21
  • 2018-05-28
  • 2012-01-06
  • 2021-10-25
  • 2021-06-15
  • 1970-01-01
相关资源
最近更新 更多