无法连接到数据库?

时间:2014-04-04 04:35:40

标签: php mysql

这个PHP对我不起作用,它不会连接 这是我的代码

<?php
$server   = "localhost";
$database = "induadmi_db";
$username = "induadmi_main";
$password = "password";

$mysqlConnection = mysql_connect($server, $username, $password);
if (!$mysqlConnection)
{
  echo "Please try later.";
}
else
{
mysql_select_db($database, $mysqlConnection);
}
?>

2 个答案:

答案 0 :(得分:-1)

尝试这种风格:sample one并在link

之后参考

http://php.net/manual/en/function.mysql-connect.php

<?php
$link = mysql_connect('localhost', 'mysql_user', 'mysql_password');
if (!$link) {
    die('Could not connect: ' . mysql_error());
}
echo 'Connected successfully';
mysql_close($link);
?>

答案 1 :(得分:-2)

使用我自己的连接参数正常工作..

您需要更改此块以查看确切的错误...

if (!$mysqlConnection)
{
  die(mysql_error());
}

mysql_*)扩展程序自PHP 5.5.0起已弃用,将来会被删除。相反,应使用MySQLiPDO_MySQL扩展名。切换到PreparedStatements甚至可以更好地抵御SQL注入攻击!

所以努夫说..

切换到PDO ..

<?php
$dsn = 'mysql:dbname=induadmi_db;host=localhost';
$database = "induadmi_db";
$username = "induadmi_main";
$password = "password";
try
{
    $dbh = new PDO($dsn, $username, $password ,array(PDO::MYSQL_ATTR_INIT_COMMAND => 'SET NAMES utf8'));
    $dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
}
catch (PDOException $e)
{
    echo 'Connection failed: ' . $e->getMessage();
}