我想连接sql数据库。 我究竟做错了什么?请帮忙
<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());
}
?>
答案 0 :(得分:3)
首先,您的constants.php
文件似乎在打开的PHP标记中有拼写错误。您应该按如下方式更新文件:
<?php
// Database Constants
define("DB_SERVER", "localhost");
define("DB_USER", "root");
define("DB_PASS", "1234");
define("DB_NAME", "widget_corp");
?>
其次,常量名称不是字符串,它们是常量。您的mysql_connect()
函数应如下所示:
$connection = mysql_connect(DB_SERVER, DB_USER, DB_PASS);
类似地,mysql_select_db()
应该是:
$db_select = mysql_select_db(DB_NAME, $connection);
答案 1 :(得分:1)
你引用了你的常数:
$connection = mysql_connect('DB_SERVER','DB_USER','DB_PASS');
^-- ^-^--- etc...
一旦被引用,它们就不再是常量 - 它们的字符串恰好具有共享常量名称的内容。因此,您确实尝试连接到名为DB_SERVER
的服务器,而不是名为localhost
的服务器。试试没有引号:
$connection = mysql_connect(DB_SERVER,DB_USER,DB_PASS);
答案 2 :(得分:0)
constants.php第1行。
<?php //And not <php, this isn't HTML.
答案 3 :(得分:0)
@AbraCadaver是正确的,constants.php文件应以<?php
而不是<php
开头。
使用常量时,还需要删除单引号。
行:
$connection = mysql_connect('DB_SERVER','DB_USER','DB_PASS');
$db_select = mysql_select_db('DB_NAME', $connection);
应该是:
$connection = mysql_connect(DB_SERVER,DB_USER,DB_PASS);
$db_select = mysql_select_db(DB_NAME, $connection);