首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >从只登录MySQL的用户中检索数据

从只登录MySQL的用户中检索数据
EN

Stack Overflow用户
提问于 2015-08-24 19:10:52
回答 1查看 3.2K关注 0票数 2

我正在构建一个新的项目,并完成了我的登录/注册脚本。到目前为止,它还在工作,但是现在我需要一个新的功能,我不知道我应该如何做到这一点。

如果用户成功登录,用户将看到的第一个页面是他的配置文件。在此页面上,我使用以下查询获取数据:

代码语言:javascript
复制
<?php 
session_start();

if(empty($_SESSION)) // if the session not yet started
   session_start();

if(!isset($_SESSION['email'])) { //if not yet logged in
   header("Location: login.php");// send to login page
   exit;
}

include 'header.php';

$get = "SELECT * FROM user" or die(mysql_error());
$result_get = mysqli_query($connect, $get);
$_SESSION['data'] = mysqli_fetch_assoc($result_get);
 
?>

在我的HTML代码中,我使用以下代码获取数据:

代码语言:javascript
复制
Firstname: <?php echo $_SESSION['data']['firstname']; ?>
Lastname: <?php echo $_SESSION['data']['lastname']; ?>
Username <?php echo $_SESSION['data']['username']; ?>

现在的问题是,我只需要显示来自当前登录的用户的数据。现在,我的查询是"SELECT * FROM user“,但我认为我可以将这个查询更改为只从当前登录的用户接收数据。类似于“从用户哪里会话中选择*”之类的内容?!

我不知道怎样才能做到这一点。

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2015-08-24 19:24:05

你可以这样做:

代码语言:javascript
复制
<?php
# Store the user input username
if (isset($_SESSION['email']) && strlen($_SESSION['email']) > 0) {
    $email = $_SESSION['email'];
} else {
    // Die the error
    printf('No email address available');
    exit;
}

# Set DB connection details
$DBHost = 'localhost';
$DBUser = 'username';
$DBPass = 'password';
$DBName = 'database';
// Configure error reporting
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);

# Create a database connection for PHP to use
$link = mysqli_connect($DBHost, $DBUser, $DBPass, $DBName);
// Set encoding type to uft8
mysqli_set_charset($link, 'utf8mb4');

# Query the database
// Build the query
$query = 'SELECT `firstname`,`lastname`,`username` FROM `table` WHERE `email` = ? LIMIT 1 ';
// Prepare it
$stmt = $link->prepare($query);
// Bind in the user input data so as to avoid SQL injection
$stmt->bind_param('s', $email);
// Execute the query
$stmt->execute();
// Bind the results to some variables
$stmt->bind_result($firstname, $lastname, $username);
// Fetch the data
$stmt->fetch();
// Close the query
$stmt->close();

# Build the html
$pageHtml = '
<p>First Name: '.$firstname.'</p>
<p>Last Name: '.$lastname.'</p>
<p>User Name: '.$username.'</p>
';

# Display the html
echo $pageHtml;

再读

MySQLi手册:

http://php.net/manual/en/book.mysqli.php

关于MySQLi连接:

http://php.net/manual/en/mysqli.quickstart.connections.php

关于MySQLi准备的声明:

http://php.net/manual/en/mysqli.quickstart.prepared-statements.php

关于数据库表索引和使用它们的“位置”。双关意:)

How does database indexing work?

http://dev.mysql.com/doc/refman/5.0/en/mysql-indexes.html

票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/32189923

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档