gpt4 book ai didi

php 无法连接到 mysql 并查询用户/密码

转载 作者:行者123 更新时间:2023-11-30 00:13:09 25 4
gpt4 key购买 nike

我正在尝试让 php/mysql 工作,以便它从表单中获取用户名和密码,并检查它们是否在 mysql 表中。如果它们在表中,它应该让您登录并将您发送到index.php页面(我更改了用户/密码/数据库)

登录页面上的表单:

    <form action="db_connect.php" method="post">
<input type="text" name="username" placeholder="Username" />
<input type="password" name="password" placeholder="Password" />
<input type="submit" value="Login" class="customButton" />
</form>

db_connect.php:

    <?php 
$username = $_POST['username'];
$password = $_POST['password'];
$con = new mysqli_connect("localhost","user","password","database");
$query = mysqli_query($con,"SELECT * FROM members WHERE username='".$username."' AND password='".$password."'");
if (mysqli_num_rows($query) != 0){
$_SESSION['logged_in'] = true;
header('Location: index.php');
}else{
echo "Access denied";
}
?>

最佳答案

此代码应该适合您。

登录页面:

<form action="db_connect.php" method="POST">
<input type="text" name="username" placeholder="Username" />
<input type="password" name="password" placeholder="Password" />
<input type="submit" value="Login" class="customButton" />
</form>

在 PHP 文件中,我们首先启动一个新 session ,然后报告生成的所有错误。然后我们转义输入字符串以避免注入(inject)。然后我们检查是否设置了通过 $_POST 发送的用户名和密码或不。然后使用我们的数据库检查输入值,最后将用户重定向到他的个性化index.php

db_connect.php

<?php
session_start();
error_reporting(E_ALL); ini_set('display_errors', 1);
$con = mysqli_connect("localhost","user","password","database");
$username = $_POST['username'];
$password = $_POST['password'];
$username = mysqli_real_escape_string($con, $username);
$password = mysqli_real_escape_string($con, $password);
if(isset($username) && isset($password)){

$query = mysqli_query($con,"SELECT * FROM members WHERE username='".$username."' AND password='".$password."'");
if (mysqli_num_rows($query) > 0){
$_SESSION['logged_in'] = $user;
header("location: index.php");
}else{
echo "Access denied";
} } else { header("location: login.php"); }
?>

关于php 无法连接到 mysql 并查询用户/密码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23878806/

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