php连接MySQL数据库
大约 1 分钟
php连接MySQL数据库
1.启动apache2服务
2.启动mysql服务,按照此教程创建好students数据库和suers表,并向表中插入数据。
3.将下面代码命名为login.php,并根据代码注释中的提示修改MySQL连接信息,然后和此教程中的index.php文件一起放到/var/www/html/目录下,启动apache2服务,重新访问 http://IP:80/index.php (将此处IP改为自己的IP地址),测试登录功能是否正常。
<?php
$username = $_POST["username"];
$password = $_POST["password"];
#连接MySQL数据库,dbusername为登录用户名,dbpassword为登录MySQL的密码,dbname为要连接的数据库名称。
#其中,用户名和密码都要改成自己虚拟机中登录MySQL使用的用户名和密码。
$dbservername = "localhost";
$dbusername = "mysql";
$dbpassword = "MySQL#jss.";
$dbname = "students";
#创建连接
$conn = new mysqli($dbservername, $dbusername, $dbpassword, $dbname);
#检测连接
if ($conn->connect_error) {
die("连接失败: " . $conn->connect_error);
}
#echo "连接成功";
#判断账号密码是否正确
$sql = "select * from users where stuID = '".$username."' and password = '".$password."'";
$result = $conn->query($sql);
if($result->num_rows > 0){
echo "登录成功,正在跳转....";
header('Refresh:3; url=http://halorealme.com');
}
else{
echo "登录失败,请重新登录!";
header('Refresh:3; url=index.php');
}
#关闭数据库连接
$conn->close();
?>
Loading...