0

I am trying to connect to a database with PHP PDO and i keep getting this: "Error: No database selected". The code i had before PDO was working just fine. Can anyone see what i'm doing wrong? I am new to PDO.

Old Code:

$dbHost = 'localhost:3306'; $dbUser = 'username'; $dbPass = 'password'; $dbName = 'database_name'; $dbconn = mysql_connect($dbhost, $dbuser, $dbpass) or die ('Error connecting to the database!'); mysql_select_db($dbname); 

PDO Code:

$dbHost = 'localhost'; $dbUser = 'username'; $dbPass = 'password'; $dbName = 'database_name'; $dbconn = new PDO('mysql:host=$dbHost;port=3306;dbname=$dbName', $dbUser, $dbPass); 

2 Answers 2

5

Use DOUBLE QUOTES

Single quotes do not allow variables in them.

For example:

$dbconn = new PDO("mysql:host=$dbHost;port=3306;dbname=$dbName", $dbUser, $dbPass); 

Or better as to make sure everything is escaped correctly:

$dbconn = new PDO("mysql:host={$dbHost};port=3306;dbname={$dbName}", $dbUser, $dbPass); 
Sign up to request clarification or add additional context in comments.

4 Comments

hmm...tried both ways (dumb mistake on my part with the quotes). Although, i still get "ERROR: no database selected"
@ryanpitts1 make sure all of your variables are correct ^_^
Ok, i blame myself for trying to do things too quick and not thinking it through. I believe it was actually a different piece of the code that was using mysql_query(). I created a blank page with just the above code (with the sprintf - thanks for that suggestion) and all is well. Thanks for the quick help, sorry to waste anyone's time. ;)
@ryanpitts1 no problem ^_^ happy to help :-)
2

Alternative to Neal's answer using sprintf to get your variables out of the strings:

$dbconn = new PDO( sprintf('mysql:host=%s;dbname=%s', $dbHost, $dbName), $dbUser, $dbPass ) 

Also to make sure the resulting string is correct you should print it:

print sprintf('mysql:host=%s;dbname=%s', $dbHost, $dbName); 

The port 3306 is default for MySQL and not really necessary to specify.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.