1

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

3
  • Are you connecting to the same mysql instance as your phpmyadmin? Commented Mar 13, 2020 at 7:00
  • @LuckyGrewal. I belive people are downvoting because you are not helping to narrow down the issue, for example, you should put the error message you are getting. The answer to this question could be anything (btw, i did not downvote you :) ) Commented Mar 13, 2020 at 10:20
  • Sometimes the phpadmin UI do not show a rogue space/character prefixing or suffixing the DB name... you can verify that DB name in the data folder. Commented Jun 2, 2024 at 10:33

1 Answer 1

5

It's either

  • a spelling error. Simply check the names again.
  • or the PHP code and PHPMyAdmin are connecting to different databases

The latter 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 PHP, using either 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

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.