Jump to content

Converting your database connection into variables?


Guest

Recommended Posts

Hi Everyone,

 

I'm a little confused as to how to convert my database connection information into variables? Below I've listed a below example of what I'm trying to do but it's not working. What am I doing wrong? Thanks everyone!

 

<?php

$password = "mypassword"
$username = "myusername"
$mydatabase= "mydatabase"
$localhost = "localhost"

$connect_error = 'Sorry we\'re experiencing connection issues';
mysql_connect("$localhost","$username","$password") or die($connect_error);
mysql_select_db('$mydatabase') or die($connect_error);

?>

This isn't going to cause an error, but it's just not good programming:

("$localhost","$username","$password")

 

Should be

($localhost, $username, $password)

 

No need to put them in strings, it takes longer to process when you do (it's a small amount but if you do that for every string variable it matters).

 

 

What IS causing your error is that you've done it with single quotes for your DB name.

mysql_select_db('$mydatabase') or die($connect_error);

 

 

You are literally connecting to $mydatabase not the value stored in $mydatabase.

Change to

mysql_select_db($mydatabase) or die($connect_error);

Hey Everyone,

 

Thanks for the replies. I figured out what I was doing wrong. Total rookie mistake. I forgot the ; at the end of my variables. The code below now works.

 

<?php

 

$password = "password";

$username = "username";

$mydatabase = "mydatabase";

$localhost = "localhost";

 

$connect_error = 'Sorry we\'re experiencing connection issues';

mysql_connect($localhost,$username,$password) or die($connect_error);

mysql_select_db($mydatabase) or die($connect_error);

 

?>

You should always develop with error reporting set up to display all errors. Make sure you have the follwoing directives set in your php.ini file, and restart apache.

 

error_reporting = -1

display_errors = On

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.