I am trying to create a database connection file so that multiple pages will have a constant connection to the database. I am trying to understand why one set of code works as far as linking to the database is concerned, whereas the other set of code fails. Please help me understand.
Here is the code that works:
$db_connect = mysql_connect('host_name', 'user_name', 'user_password');
if(!$db_connect){
die('Not connected :' . mysql_error());
}
$db_select = mysql_select_db("dispatch", $db_connect);
if(!$db_select){
die('No database :' . mysql_error());
}
I am able to establish a working connection to the server, as well as selecting a table and running a query.
Here is the code that fails (I want my code to look like this code but I do not understand why this fails to connect to the server.):
$db_host = "host_name";
$db_user = "user_name";
$db_pass = "user_password";
$db_name = "user_table";
$db_connect = mysql_connect("$db_host", "$db_user", "$db_pass") or die ("Could not connect to MySQL");
I even tried this code, and it still fails:
$db_host = "host_name";
$db_user = "user_name";
$db_pass = "user_password";
$db_name = "user_table";
$db_connect = @mysql_connect("$db_host", "$db_user", "db_pass") or die ("Could not connect to MySQL");
$db_select = @mysql_select_db("$db_name") or die ("Could not connect to database");
Please note that I have tried to switch from single quote ( '' ) to double quotes ( " " ) to no avail.
Please help me understand. Please not ask why I don't just use the code that works. I want to understand why the second sets of code DO NOT work.
Please also note that this is only my second time using Stack Overflow, and I am still trying to get the hang of it. Thanks.
Hit me back...
mysql_*
functions in new code. They are no longer maintained, are officially deprecated and can be dangerous in live code. See the red box? Learn about prepared statements instead, and use PDO or MySQLi - this article will help you decide which. If you choose PDO, here is a good tutorial. – Jimbo May 16 '13 at 14:33mysql_error()
when you run the non-working code? – andrewsi May 16 '13 at 14:34