我在LAMP下测试我的电脑上的本地登录数据库页面.即使我可以从终端连接到mysql,我也不能从php脚本中这样做.我在网上看了一遍,但每一个我只是在一个或另一个变体中的代码
<!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>
Run Code Online (Sandbox Code Playgroud)
还有另一个页面,它使用用户名和密码,然后通过POST方法将其传递给此页面,但此页面立即显示我的连接错误.我事件尝试用if而不是或死,但仍然无法连接.
您必须将变量传递给连接函数并显示有意义的错误说明:
$username = $_POST['username'];
$password = $_POST['password'];
/* connect to the db */
$connection = mysql_connect('localhost', $username, $password) or die(mysql_error());
Run Code Online (Sandbox Code Playgroud)
您的脚本存在SQL注入攻击的风险.
如果可以,您应该停止使用mysql_*功能.这些扩展已在PHP 7中删除.了解PDO和MySQLi的预处理语句并考虑使用PDO,这真的不难.
你真的不希望以这种方式连接到你的数据库,但它留下了太多的机会.当你使用密码时,你真的应该使用PHP的内置函数来处理密码安全性.如果您使用的PHP版本低于5.5,则可以使用password_hash() 兼容包.