2015-11-19 69 views
0

我正在LAMP下测试本地登录数据库页。即使我可以从终端连接到MySQL,我不能从一个PHP脚本。我找遍了整个网络,但每次我走到哪里它只是将下面的代码在一个变化或其他MySQL不连接到数据库

<!DOCTYPE HTML5> 
<html> 
    <meta http-equiv="content-type" content="text/html; charset=utf-8"/> 
    <link rel="stylesheet" type="text/css" href="style.css"> 
    <head> 
    </head> 
    <body> 

    <?php 

    $username = $_POST['username']; 
    $password = $_POST['password']; 

    /* connect to the db */ 
    $connection = mysql_connect('localhost', 'username', 'password') or die ("Connect error"); 
    mysql_select_db('myDatabase',$connection); 
    /* show tables */ 
    $res = mysql_query("SHOW DATABASES", $connection) or die ("No Show Database"); 
    while ($row = mysql_fetch_row($res)) 
    { 
     echo $row[0], '<br/>'; 
    } 

    ?> 

    </body> 
</html> 

还有另外一个页面,需要用户名和密码,然后将它传递给通过POST方法这个网页,但是此页面会立即向我显示连接错误。我的事件试图用如果其他而不是或死但仍然无法连接。

+4

'或死(​​“连接错误”);'没有帮助你。 ''或死(mysql_error())'',死或死(“无显示数据库”);' –

+0

[您的脚本存在SQL注入攻击的风险。](http://stackoverflow.com/questions/60174/how-can-i-prevent-sql -injection-in-php) –

+2

如果可以,你应该[停止使用'mysql_ *'函数](http://stackoverflow.com/questions/12859942/why-shouldnt- I-使用MySQL的函数式的PHP)。 [这些扩展](http://php.net/manual/en/migration70.removed-exts-sapis.php)已在PHP 7中删除。了解[编写]​​(http://en.wikipedia.org/ wiki/Prepared_statement)语句[PDO](http://php.net/manual/en/pdo.prepared-statements.php)和[MySQLi](http://php.net/manual/en/mysqli.quickstart .prepared-statements.php)并考虑使用PDO,[它确实不难](http://jayblanchard.net/demystifying_php_pdo.html)。 –

回答

5

您必须将变量传递给连接功能,并显示一个有意义的错误描述:

$username = $_POST['username']; 
$password = $_POST['password']; 

/* connect to the db */ 
$connection = mysql_connect('localhost', $username, $password) or die(mysql_error()); 

Your script is at risk for SQL Injection Attacks. 如果可以的话,你应该stop using mysql_* functionsThese extensions已在PHP 7中删除。了解有关PDOMySQLiprepared对帐单,并考虑使用PDO,it's really not hard

你真的不想以这种方式连接到你的数据库,但它留下了太多的机会。而当你使用密码时,你应该使用PHP的built-in functions来处理密码安全。如果您使用的PHP版本低于5.5,则可以使用password_hash()compatibility pack

+0

注射?哪里? –

+0

传入数据库函数@vp_arth的不清洁变量。我试图在通过时将它关掉。 –

+0

如果你关于'user/pass' - 它的意思是接收不干净的变量(按原样)。但是如果你关于查询,没有任何连接的'show databases'怎么会有sql注入的风险? –