php - 无法使用 PHP 从 MySQL 获取变量
问题描述
我需要从 MySQL DB(它肯定存在)中获取一些数据来继续分析它。所以,我的代码中有什么:
if (count($errors) == 0)
$password = md5($password);
$query = "SELECT username, password, email FROM trackowners WHERE username='$username' AND password='$password'";
$results = mysqli_query($db, $query);
if (mysqli_num_rows($results) == 1) {
///////////
$_SESSION['username'] = $username;
$_SESSION['success'] = "You are now logged in";
$_SESSION['email'] = $email;
header('location: index.php');
}else {
array_push($errors, "Wrong username/password combination");
} }
然后我尝试使用变量 $_SESSION['username'] 并通过电子邮件发送:
<?php if (isset($_SESSION['username'])) : ?>
<p>Welcome <strong><?php echo $_SESSION['username']; ?></strong> // Here are your profile settings.</p>
<p> <a href="index.php?logout='1'" style="color: red;">logout</a> </p>
<?php endif ?>
<?php if (isset($_SESSION['username'])) : ?>
<p>Your e-mail<strong><?php echo $_SESSION['email']; ?></strong> //</p>
<?php endif ?>
在这里我得到了用户名变量,但我无法从电子邮件变量中得到任何东西。有什么问题?
提前致谢!
解决方案
我对您的代码有很多疑问(不要使用 MD5 进行密码散列,而是使用PHP 内置散列方法)。但是继续@Nicolas 的帖子
编辑遵循杰伊布兰查德的建议
// Make sure your session is started
session_start();
if (count($errors) == 0){
// Make sure to store your passwords with the same function
$password = password_hash($password, PASSWORD_DEFAULT );
// Prepare your query with placeholders
$query = $pdo->prepare('SELECT username, password, email FROM trackowners WHERE username=? AND password=?');
// Execute your query
if($query->execute(array($username, $password)))
{
// Loop through result set
while ($row = $query->fetch(PDO::FETCH_ASSOC)) {
$_SESSION['username'] = $row['username'];
$_SESSION['email'] = $row['email'];
$_SESSION['success'] = "You are now logged in";
}
header('location: index.php');
}
else
{
array_push($errors, "Wrong username/password combination");
}
}
正如@Nicolas 所提到的,阅读了Prepared statements以防止 sql 注入。
推荐阅读
- javascript - jQuery Slick Slider:如何滚动不到一整张幻灯片
- web-scraping - 在 python 3.6 中使用 beautifulsoup4 抓取网站以获取产品信息
- python - Python -- 值错误:索引 968 处不支持的格式字符 ',' (0x2c)
- php - 链接到外部站点时出现相对 url 的问题
- docker - OCI 运行时失败 container_linux:345 启动容器进程导致 process_linux init 导致 rootfs_linux:58 挂载导致 perm 拒绝未知
- python-3.x - 发送接收数据不能正常工作
- select - 以相同语法划分和更新字段的子字符串
- java - AndroidStudio 因内部异常而失败
- pandas - 创建字典
- r - 闪亮的部署错误:值 [[3L]](cond) 中的错误:“闭包”类型的对象不是子集