2015-11-19 77 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注入的風險? –