PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Wednesday, February 9, 2022

[FIXED] Mysql - Couldn't connect unknown database 'databasename' error

 February 09, 2022     mysql, pdo, php, phpmyadmin     No comments   

Issue

I am using PDO to connect to mySql database. I am not able to connect to any database that I create although I can connect to already created databases( already created by default). I am using wamp server.

<?php
try{
$dbh=new PDO("mysql:host=localhost;dbname=mydata","root","");
}catch(Exception $e){
    die("ERROR: Couldn't connect. {$e->getMessage()}");
}
?>

If i substitute mydata with mysql which is previously created database in wamp server, then the code works perfectly. The only problem is with the databases that I create. I have tried giving mydata the same privileges as mysql database but it doesn't work.

enter image description here


Solution

Your code and your phpmyadmin are simply connecting to different database servers. It could happen, for example, if you have multiple database servers on your PC installed.

To get a proof, run the following query in phpmyadmin:

show databases;

And then run the same query in PDO:

$host = 'your db host';
$user = 'your db username';
$pass = 'your db password';

$pdo = new PDO("mysql:host=$host", $user, $pass, [PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION]);
$databases = $pdo->query('show databases')->fetchAll(PDO::FETCH_COLUMN);
var_dump($databases);

or mysqli

$host = 'your db host';
$user = 'your db username';
$pass = 'your db password';

mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
$mysqli = mysqli_connect($host, $user, $pass);
$databases = $mysqli->query('show databases')->fetch_all();
var_dump($databases);

and compare the output. It will show you that either there is a spelling error or indeed phpmyadmin and PHP are connected to different database servers.

Then you can check the configuration file in PHPmyAdmin to make sure it connects to the proper server



Answered By - Your Common Sense
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home
View mobile version

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing