Reputation: 11
I want to connect sql database. What am I doing wrong? Please help
<php
// Database Constants
define("DB_SERVER", "localhost");
define("DB_USER", "root");
define("DB_PASS", "1234");
define("DB_NAME", "widget_corp");
?>
<?php
require("constants.php");
//1. Create a database connection
$connection = mysql_connect('DB_SERVER','DB_USER','DB_PASS');
if(!$connection) {
die("Database connection failed: " . mysql_error());
}
//2. Select a database to use
$db_select = mysql_select_db('DB_NAME', $connection);
if(!$db_select) {
die("Database selection failed: " . mysql_error());
}
?>
Upvotes: 1
Views: 983
Reputation: 360572
You've quoted your constants:
$connection = mysql_connect('DB_SERVER','DB_USER','DB_PASS');
^-- ^-^--- etc...
Once quoted, they're no longer constants - they're strings that happen to have contents that share the name of a constant. So you're literally trying to connect to a server named DB_SERVER
, instead of the server named localhost
. Try without quotes:
$connection = mysql_connect(DB_SERVER,DB_USER,DB_PASS);
Upvotes: 1
Reputation: 53198
Firstly, your constants.php
file seems to have a typo in the opening PHP tag. You should update the file as follows:
<?php
// Database Constants
define("DB_SERVER", "localhost");
define("DB_USER", "root");
define("DB_PASS", "1234");
define("DB_NAME", "widget_corp");
?>
Secondly, constant names aren't strings, they're constants. Your mysql_connect()
function should look like this:
$connection = mysql_connect(DB_SERVER, DB_USER, DB_PASS);
And similarly, mysql_select_db()
should be:
$db_select = mysql_select_db(DB_NAME, $connection);
You should be advised though, that the mysql_*()
family of function is now deprecated. You should consider using MySQLi or PDO for security and longevity.
Upvotes: 3
Reputation: 804
@AbraCadaver is correct that the constants.php file should start with <?php
not <php
.
You also need to remove the single quotes when using your constants.
Lines:
$connection = mysql_connect('DB_SERVER','DB_USER','DB_PASS');
$db_select = mysql_select_db('DB_NAME', $connection);
Should be:
$connection = mysql_connect(DB_SERVER,DB_USER,DB_PASS);
$db_select = mysql_select_db(DB_NAME, $connection);
Upvotes: 0
Reputation: 174957
constants.php line 1.
<?php //And not <php, this isn't HTML.
Upvotes: 0