这是我的第一个php代码,我正在尝试使用用户名=" root"连接到数据库。和密码=" root"
我有一个名为dbConnection.php
的连接文件
如下:
<?php
echo "in connection file";
$hostname = "localhost";
$username = "root";
$password = "root";
$db = "ledDB";
echo "<br> db-connection : vars definde ";
//connection to the database
$conn = mysql_connect($hostname, $username, $password)
or die("Unable to connect to MySQL");
echo "Connected to MySQL<br>";
echo "db-connection : initilize connection ";
mysql_select_db($db);
echo "db-connection : connection done";
// Check connection
echo "Connected successfully";
?>
我在名为what.php的文件中调用它:
<?php
echo "Hello";
include "dbConnection.php";
echo "ohhhh";
?>
这将返回状态代码500,即内部服务器错误
但我想知道修复它的错误是什么我如何收到错误消息?
我试过
$ conn = mysql_connect($ hostname,$ username,$ password) 或死(&#34;无法连接到MySQL&#34;);
但它没有返回任何东西。
任何人都能帮帮我吗?
答案 0 :(得分:0)
如果您在localhost上有密码,请使用密码,否则请将其留空
$con = mysqli_connect("localhost","root","yourpassword","yourdb");
答案 1 :(得分:0)
malloc
答案 2 :(得分:0)
你是mysqli_connect()方法。
<?php
echo "in connection file";
$hostname = "localhost";
$username = "root";
$password = "root";
$db = "ledDB";
echo "<br> db-connection : vars definde ";
//connection to the database
$conn = mysqli_connect($hostname, $username, $password)
or die("Unable to connect to MySQL");
echo "Connected to MySQL<br>";
echo "db-connection : initilize connection ";
mysqli_select_db($conn,$db);
echo "db-connection : connection done";
// Check connection
echo "Connected successfully";
?>
答案 3 :(得分:0)
首先要将您的连接方法更改为mysqli或我个人喜爱的PDO。 PDO示例:
class db extends pdo{
//Website Variables
public $sitedb = '';
public $siteconfig;
public $sitesettings = array(
'host' => 'localhost',
'database' => 'yourdb',
'username' => 'youruser',
'password' => 'yourpass',
);
public function __construct(){
$this->sitedb = new PDO(
"mysql:host={$this->sitesettings['host']};" .
"dbname={$this->sitesettings['database']};" .
"charset=utf8",
"{$this->sitesettings['username']}",
"{$this->sitesettings['password']}"
);
$this->sitedb->setAttribute(PDO::ATTR_DEFAULT_FETCH_MODE, PDO::FETCH_ASSOC);
}
}
$db = new db();
然后,您可以在包含db.php页面后将PDO类扩展到新类。 示例选择:
class yourclass extends db {
public function SelectUsers() {
global $db;
$query = <<<SQL
SELECT email
FROM users
WHERE active = :active
SQL;
$resource = $db->sitedb->prepare( $query );
$resource->execute( array (
':active' => 1,
));
$count = $resource->rowCount();
foreach($resource as $user){
$this->email = $user['email'];
}
}
}