i_me_mine
i_me_mine

Reputation: 1433

Can't properly connect to MySql with PDO

First of all I just switched all my PHP files to use PDO, so that's happy. However I'm not very experienced with PHP let alone PDO so I'm having a problem. I run the following query in my SQL databse and it returns the correct values.

SELECT * 
FROM table_gon_0621_516
WHERE id =  '1'

Now I use this in my PHP like so

require_once ("../Android/connect_db.php");

$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$table_name = 'table_gon_0621_516';

try { 

    $names = $db->query("
        SELECT * 
        FROM `".$table_name."` 
        WHERE `id` = '1'
        ");

    $rows = $names->fetchAll(PDO::FETCH_ASSOC);
    $col_map = array_flip($rows);
    echo '<pre>', print_r($rows, true), '</pre>';
} catch (PDOException $e){
    die($e->getMessage());
}    

and i get this error in my browser

SQLSTATE[3D000]: Invalid catalog name: 1046 No database selected

This is my connection code

<?php

$config['db'] = array (
    'host'      => 'localhost',
    'username'  => 'admin',
    'password'  => 'xxxx', //checked and correct
    'dbname'    => 'xxxx_beta' //checked and correct
);

$db = new PDO(
    'mysql:host = '.$config['db']['host'].';
    dbname = '.$config['db']['dbname'], 
    $config['db']['username'], 
    $config['db']['password']
);
?>

This page loads correctly, there are no errors and I connect successfully. What am I doing wrong?

EDIT

I changed

$data = $names->fetchAll(PDO::FETCH_ASSOC);

to

$data = $names->fetch(PDO::FETCH_ASSOC);

and I'm still having the same problem. I also updated the code above to show this change

2nd EDIT

I changed my code above and now receive a new message, I'm assuming I'm not connected?

Upvotes: 3

Views: 232

Answers (1)

peterm
peterm

Reputation: 92785

Change

$db = new PDO(
    'mysql:host = '.$config['db']['host'].';
    dbname = '.$config['db']['dbname'], 
    $config['db']['username'], 
    $config['db']['password']
);

to

$db = new PDO('mysql:host='.$config['db']['host'].';dbname='.$config['db']['dbname'], 
    $config['db']['username'], 
    $config['db']['password']
);

or

$db = new PDO(
    "mysql:host={$config['db']['host']};dbname={$config['db']['dbname']}",
    $config['db']['username'], 
    $config['db']['password']
);

Apparently MySql PDO driver doesn't like spaces in DSN.

mysql:host='.$config['db']['host'].';dbname='.$config['db']['dbname']
          ^^                               ^^

Upvotes: 4

Related Questions