-2

我在一个名为navbar.php的文件上有一个导航栏脚本。我将此文件包含在我网站所有其他页面的顶部。我现在要做的是使用登录者的名称自定义导航栏。假设我有一个名为account-process.php的 php 文件,其中包含一个变量$name = 'Bob'。我无法让这个变量显示在导航栏中。

这是我的account-process.php

<?PHP
//VARS: gets user input from previous sign in page and assigns it to local variables
//$_POST['signin-email'];
//$_POST['signin-pass'];
$signin_email = $_POST['signin-email'];
$signin_pass = $_POST['signin-pass'];

// connects to MySQL database
include("config.inc.php");
$link = mysql_connect($db_host,$db_user,$db_pass);
mysql_select_db($db_name,$link);

// checking for user input in the table
$result = mysql_query("SELECT * FROM table WHERE email = '$signin_email' AND password = '$signin_pass'");   
if (mysql_num_rows($result) > 0) { // if the username and password exist and match in the table
    echo "Account Found";
    $account_arr = mysql_fetch_array($result); // contains all the data from the user's MySQL row
    echo print_r($account_arr);
}
else { // if username and password don't match or they aren't found in the table
    echo "The email or password you entered is incorrect.";
}
?>

我正在尝试访问navbar.php$account_arr中的变量,以便可以在顶部显示用户名。我尝试在navbar.php中包含account-process.php ,然后在导航栏的 html 中访问该变量,但是当我尝试这样做时,页面只是显示为空白。<?php include('account-process.php') ?>

navbar.php只是为带有一些信息的固定导航栏提供基本脚本。为什么当我尝试在其中包含 php 文件时它变成空白?

谢谢

4

1 回答 1

1

将导航栏更改为 PHP 文件并使用会话。-编辑- 花了很长时间发布。将其保留为 PHP。

帐户-process.php:

<?php
session_start();
//VARS: gets user input from previous sign in page and assigns it to local variables
//$_POST['signin-email'];
//$_POST['signin-pass'];
$signin_email = $_POST['signin-email'];
$signin_pass = $_POST['signin-pass'];

// connects to MySQL database
include("config.inc.php");
$link = mysql_connect($db_host,$db_user,$db_pass);
mysql_select_db($db_name,$link);

// checking for user input in the table
$result = mysql_query("SELECT * FROM table WHERE email = '$signin_email' AND password = '$signin_pass'");   
if (mysql_num_rows($result) > 0) { // if the username and password exist and match in the table
    echo "Account Found";
    $account_arr = mysql_fetch_array($result); // contains all the data from the user's MySQL row
    echo print_r($account_arr);
    $_SESSION['name']=$account_arr['username'];
}
else { // if username and password don't match or they aren't found in the table
    echo "The email or password you entered is incorrect.";
}

?>

导航栏.php:

<?php
session_start();
echo "<div><p>Hello, my name is " . $_SESSION['name'] . ".</p></div>";
?>

会话数据存储在一个名为的 cookie 中,该 cookiePHPSESSID在浏览会话结束后过期。

session_start()您可以使用该功能启动或恢复会话。<!DOCTYPE html>如果页面包含非 PHP 生成的 HTML ,则必须在此之前调用。

数据存储在一个名为 的超全局关联数组中$_SESSION。可以在调用 session_start 的任何页面上向/从该变量发送和修改信息。

如果您不想使用会话,您可以创建自己的 cookie 并使用$_COOKIE超全局。

更多信息:

http://php.net/manual/en/function.session-start.php

http://www.w3schools.com/php/php_sessions.asp

http://www.w3schools.com/php/php_cookies.asp

于 2014-08-31T03:01:20.430 回答