gpt4 book ai didi

php - MySQL 连接不上数据库

转载 作者:行者123 更新时间:2023-12-01 00:40:28 25 4
gpt4 key购买 nike

我正在 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 方法将其传递给该页面,但该页面立即显示连接错误。我尝试使用 if else 而不是 or die 但仍然无法连接。

最佳答案

您必须将变量传递给连接函数并显示有意义的错误描述:

$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_* functions . These extensions已在 PHP 7 中删除。了解 prepared PDO 的声明和 MySQLi并考虑使用 PDO,it's really not hard .

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

关于php - MySQL 连接不上数据库,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33813472/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com