2016-01-13 49 views
1

我正在设计一个带有登录页面的网站。登录部分和从数据库抓取工作正常。但我想在登录后在主页上显示用户名。我使用session_start()。但用户名不显示。我在这里查了类似的问题,但没有一个是我的答案。以下是代码: PHP代码:在网站上登录后显示用户名

$email = mysqli_real_escape_string($con,$_POST['user']); 
$pass = mysqli_real_escape_string($con,$_POST['pass']); 
$sel_user = "select * from admins where email='$email' AND password='$pass'"; 
$run_user = mysqli_query($con, $sel_user); 
$check_user = mysqli_num_rows($run_user); 
if($check_user>0) 
{ 
$_SESSION['email']=$email 
echo "<script>window.open('index2.html','_self')</script>"; 
} 
else { 
echo "<script>alert('Email or password is not correct, try again!')</script>"; 
} 

index2.html:

<?php 
     session_start(); 
?> 
    <div class="inline-block"> 
           <h5 class="no-margin"> Welcome </h5> 
           <h4 class="no-margin"> <?php echo $_SESSION['email']; ?> </h4> 
           <a class="btn user-options sb_toggle"> 
            <i class="fa fa-cog"></i> 
           </a> 
          </div> 
+1

你必须在你的php脚本的每个文件中包括'start_session()',包括你在哪里设置'$ _SESSION ['email']' – noor

+1

你在html文件中使用php标签。将index_2.html更改为index_2.php ...完成 –

+0

您必须在第一个文件中找到的$ _SESSION ['email'] = $ email末尾放置分号。 –

回答

0

尝试以下代码:

第一代码

session_start(); 
$email = mysqli_real_escape_string($con,$_POST['user']); 
$pass = mysqli_real_escape_string($con,$_POST['pass']); 
$sel_user = "select * from admins where email='$email' AND password='$pass'"; 
$run_user = mysqli_query($con, $sel_user); 
$check_user = mysqli_num_rows($run_user); 
if($check_user>0) 
{ 
    $_SESSION['email']=$email 
    echo "<script>window.open('index2.html','_self')</script>"; 
} 
else { 
    echo "<script>alert('Email or password is not correct, try again!')</script>"; 
} 

index2.php

<?php session_start(); ?> 
<div class="inline-block"> 
    <h5 class="no-margin"> Welcome </h5> 
    <h4 class="no-margin"> <?php echo $_SESSION['email']; ?> </h4> 
    <a class="btn user-options sb_toggle"> 
     <i class="fa fa-cog"></i> 
    </a> 
</div> 

它应该工作。

+0

我已经在我的htaccess中添加了AddType application/x-httpd-php5 .html .htm。所以我可以在我的html中运行php.but当你的代码提到我应该添加一个会话开始也在我的PHP代码。所以它现在正在工作。 thhks – user3696174

+0

欢迎,很高兴为您效劳! –

+0

*“有一个很大的错误,就是你不能在.html文件中运行PHP。” - 这是错误的,应该从答案中丢弃,或修改为读取如下内容:*“你需要指示Apache来处理.html文件作为PHP“*,就像OP说的那样。 –

相关问题