gpt4 book ai didi

php - 从 mySql 数据库中为 php 用户 session 获取数据

转载 作者:太空宇宙 更新时间:2023-11-03 11:36:48 24 4
gpt4 key购买 nike

我对 PHP 和 mySQL 比较陌生,我正在尝试使用 mySQL 数据库中的字段创建用户 session 。

我设置它的方式意味着我通过对照数据库检查输入登录表单的两个字段(用户名和密码)来获得一个 session ,但我无法从数据库中检索任何其他数据并且将其添加到 session 中。

如何从数据库中检索其他数据并将其添加到新 session 中?

<?php
require('db.php');
session_start();

// If form submitted, insert values into the database.
if (isset($_POST['username'])){
// removes backslashes
$username = stripslashes($_REQUEST['username']);
//escapes special characters in a string
$username = mysqli_real_escape_string($con,$username);
$password = stripslashes($_REQUEST['password']);
$password = mysqli_real_escape_string($con,$password);
//Checking is user existing in the database or not
$query = "SELECT * FROM `users` WHERE username='$username' and password='".md5($password)."'";
$result = mysqli_query($con,$query) or die(mysql_error());
$rows = mysqli_num_rows($result);
if($rows==1){
//This one works
$_SESSION['username'] = $username;

//This one doesn't
$_SESSION['email'] = $rows ['email'];

// Redirect user to index.php
header("Location: index.php");
}else{
echo "<div class='form'>
<p>Username/password is incorrect.</p>
<br/>Click here to <a href='login.php'>Login</a></div>";
}
}else{
}
?>

最佳答案

$rows 是计数器变量(包含记录数),这就是为什么不起作用。

像下面这样:-

....previous code as it is
$result = mysqli_query($con,$query) or die(mysql_error());
$row = mysqli_fetch_assoc($result); //fetch record
$rows = mysqli_num_rows($result);
if($rows==1){
$_SESSION['email'] = $row['email'];
header("Location: index.php");
}...rest code as it is

注意:-

1.不要使用md5密码加密,使用密码散列技术。

2.使用 mysqli_*prepared statements 来防止您的代码SQL 注入(inject)

关于php - 从 mySql 数据库中为 php 用户 session 获取数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45234580/

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