Ошибка sqlstate hy000 1049 unknown database

I have this error when i use php artisan migrate in my Laravel project.

[PDOException]
SQLSTATE[HY000] [1049] Unknown database 'previous_db_name'

this is my database.php file :

'default' => env('DB_CONNECTION', 'mysql'),
'connections' => [

    'mysql' => [
        'driver'    => 'mysql',
        'host'      => env('DB_HOST', 'localhost'),
        'database'  => env('DB_DATABASE', 'current_db_name'),
        'username'  => env('DB_USERNAME', 'root'),
        'password'  => env('DB_PASSWORD', ''),
        'charset'   => 'utf8',
        'collation' => 'utf8_unicode_ci',
        'prefix'    => '',
        'strict'    => false,
    ],
],

I saw this error in this question and this question but none of them was not helpful.

Создала БД на phpmyadmin , пытаюсь подключиться к ней и вывести массивом данные на экран, но сайт выдает ошибку ,что не видит базы с таким названием,пробовала все имена баз,никакую не видит.
Fatal error: Uncaught PDOException: SQLSTATE[HY000] [1049] Unknown database ‘mvc_site’ in C:wamp64wwwmodelsNews.php on line 17
PDOException: SQLSTATE[HY000] [1049] Unknown database ‘mvc_site’ in C:wamp64wwwmodelsNews.php on line 17

Вот код файла News.php

class News {
    
    public static function getNewsList(){
        //Запрос к БД 
        $host = 'localhost';
        $dbname = 'mvc_site';
        $user = 'root';
        $password = '';
        $db = new PDO ("mysql:host=$host; dbname=$dbname", $user, $password);
        
        $newsList = array();
        
        $result = $db->query('SELECT id, title, date, short_content'
                .'FROM news'
                .'ORDER BY date DESC'
                .'LIMIT 10');
        
        $i=0; 
        while ($row = $result -> fetch()){
            $newsList[$i]['id'] = $row['id'];
            $newsList[$i]['title'] = $row['title'];
            $newsList[$i]['date'] = $row['date'];
            $newsList[$i]['short_content'] = $row['short_content'];
            $i++;
        }
        return $newsList;
    }
}

17 строка это подключение PDO , подсвечивает что имя базы неверное,но все символ в символ идентично. Заранее спасибо за помощь

Обновление: я перенесла проект на open server, теперь базу видит , но не выводит данные таблицы, пишет что ошибка в цикле while , но не понимаю где там ошибка

Same exact problem with exact reported issues. Question here is whether there is a way to get SQL query for automatically creating all DBs and tables Firefly requires. That would be far more convenient. Also it would be awesome if there is docker image with integrated database engine.

Some if the errors I have got a long the way (I still haven’t succeeded installing docker image of firefly)

[root@localhost ~]# docker exec -it 71a685eeed02 php artisan migrate —seed

In Connection.php line 664:

SQLSTATE[01000]: Warning: 1265 Data truncated for column ‘migration’ at row 1 (SQL: insert into migrations (migration, batch) values (2016_06_16_000000_create_support_tables, 1))

In PDOStatement.php line 107:

SQLSTATE[01000]: Warning: 1265 Data truncated for column ‘migration’ at row 1

In PDOStatement.php line 105:

SQLSTATE[01000]: Warning: 1265 Data truncated for column ‘migration’ at row 1

[root@localhost ~]# docker exec -it 71a685eeed02 php artisan firefly:upgrade-database

In Connection.php line 664:

SQLSTATE[42S22]: Column not found: 1054 Unknown column ‘accounts.deleted_at
‘ in ‘where clause’ (SQL: select accounts.* from accounts left join ac count_types on account_types.id = accounts.account_type_id where account_types.type in (Default account, Asset account) and accounts.d eleted_at is null)

In PDOConnection.php line 79:

SQLSTATE[42S22]: Column not found: 1054 Unknown column ‘accounts.deleted_at
‘ in ‘where clause’

In PDOConnection.php line 77:

SQLSTATE[42S22]: Column not found: 1054 Unknown column ‘accounts.deleted_at
‘ in ‘where clause’

SQLSTATE[42S22]: Column not found: 1054 Unknown column ‘batch’ in ‘order cl
ause’ (SQL: select migration from migrations order by batch asc, mig ration asc)

SQLSTATE[22001]: String data, right truncated: 1406 Data too long for colum
n ‘migration’ at row 1 (SQL: insert into migrations (migration, batch
) values (2016_06_16_000000_create_support_tables, 1))

SQLSTATE[01000]: Warning: 1265 Data truncated for column ‘migration’ at row 1 (SQL: insert into migrations (migration, batch) values (2016_06_16_000000_create_support_tables, 1))

Post Views: 79

In this tutorial I’m going to describe how to fix “unknown database in laravel Bug”

SQLSTATE[HY000] [1049] Unknown database ‘laravel’ (1049)

Whenever you migrate in laravel and its showing unknown database name, please follow some easy steps its helpful for you.

php artisan migrate

When you stuck this kind of bug you have to go .env folder and check your database name and put same name as “edureka” in .env folder

then go to phpmyadmin and put database name “edureka” then run this command —

php artisan c:cache

php artiasn:migrate 
php artiasn:serve

http://127.0.0.1:8000/

Login successfully …

  • Author
  • Recent Posts

Tagged : database / laravel / phpmyadmin / unknown

I am getting this error while trying to save an object into DB.

SQLSTATE[HY000] [1049] Unknown database ‘laravel’ (SQL: insert into cards (card_price, active, updated_at, created_at) values (0, 1, 2019-10-10 15:14:43, 2019-10-10 15:14:43))

.env

DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=cardgame
DB_USERNAME=root
[email protected]!

Database.php

'mysql' => [
        'driver' => 'mysql',
        'url' => env('DATABASE_URL'),
        'host' => env('DB_HOST', '127.0.0.1'),
        'port' => env('DB_PORT', '3306'),
        'database' => env('DB_DATABASE', 'forge'),
        'username' => env('DB_USERNAME', 'forge'),
        'password' => env('DB_T_PASSWORD', ''),
        'unix_socket' => env('DB_SOCKET', ''),
        'charset' => 'utf8mb4',
        'collation' => 'utf8mb4_unicode_ci',
        'prefix' => '',
        'prefix_indexes' => true,
        'strict' => true,
        'engine' => null,
        'options' => extension_loaded('pdo_mysql') ? array_filter([
            PDO::MYSQL_ATTR_SSL_CA => env('MYSQL_ATTR_SSL_CA'),
        ]) : [],
    ],

CardController.php

  public function generateCards()
  {
  $card = new Card();
  $card->card_price = 0;
  $card->active = 1;
  $card->save();
  }

Web.php

 Route::get('/generate-cards', '[email protected]');

Card.php

class Card extends Model
{
 protected  $guarded =[];
}

Migration file

public function up()
{
    Schema::create('cards', function (Blueprint $table) {
        $table->bigIncrements('id');
        $table->integer('card_price');
        $table->integer('active');
        $table->timestamps();
    });
}

I’ve tried clearing cache and also have edited DB_PASSWORD To DB_T_PASSWORD as this corrected a similar issue earlier. Double checked the DB name, passwords etc & also other projects are already running also. I’m not able to figure it out.

Понравилась статья? Поделить с друзьями:
  • Ошибка sqlstate hy000 1045 access denied for user
  • Ошибка sqlstate 23000 integrity constraint violation
  • Ошибка sqlserver 15404 не удалось получить сведения о пользователе
  • Ошибка sqllib системная таблица sysaltfiles в экземпляре sql server
  • Ошибка sqlallochandle для драйвера в sql handle dbc